Night Warrier
Night Warrier

Reputation: 381

iOS sandbox independent file path

I am developing a simple app for iOS. And I was really surprised that when image is written like in the code below, the path stays valid before the app restarts. After the app restarts the new sandbox is created and this invalidates the previous path. I am trying to find a way to have sandbox independent file path. Is it even possible without going through the resolution cycle (i.e. FileManager.default.url...)?

    static func saveToDocument(name: String, image: UIImage) -> String? {
    guard let data = image.pngData() else { return nil; }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return nil
    }
    do {
        let file = directory.appendingPathComponent("\(name).png");
        try data.write(to: file!)
        return file?.absoluteString
    } catch {
        return nil
    }
}

Upvotes: 1

Views: 1851

Answers (1)

vadian
vadian

Reputation: 285082

Stop searching, there is no way, and there is a good reason for that: The safety of your data.

You always have to get the URL of the documents directory with FileManager.default.url(for, it's not that expensive.

Guarding the URL is not necessary, the documents folder is guaranteed to exist.

Return only the file name rather than the complete URL string and I recommend to make the function throw to hand over all errors.

enum FileError : Error {
    case noData
}

static func saveToDocument(name: String, image: UIImage) throws -> String {
    guard let data = image.pngData() else { throw FileError.noData }
    let directory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)            
    let fileURL = directory.appendingPathComponent("\(name).png")
    try data.write(to: fileURL)
    return fileURL.lastPathComponent
}

And never use NS... classes like NSURL in Swift if there is a native counterpart (URL).

Upvotes: 2

Related Questions