saoudrizwan / Disk

Delightful framework for iOS to easily persist structs, images, and data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error Creating And Saving To Subfolder

forgot opened this issue · comments

I'm getting a permissions error when trying to save data to a subfolder that is created as part of the save.

Here's the code where I'm trying to save the data:

    do {
        let data = try Data(contentsOf: url)
        let path = "Inbox/PDF/\(title)"
        try Disk.save(data, to: .documents, as: path)
    } catch let error as NSError {
        print("""
            Domain: \(error.domain)
            Code: \(error.code)
            Description: \(error.localizedDescription)
            Failure Reason: \(error.localizedFailureReason ?? "")
            Suggestions: \(error.localizedRecoverySuggestion ?? "")
            """)
    }

When I run this on the simulator, it works just fine. However, when I run it on a device, I get this response:

Domain: NSCocoaErrorDomain
Code: 513
Description: You don’t have permission to save the file “PDF” in the folder “Inbox”.
Failure Reason: You don’t have permission.
Suggestions: To view or change permissions, select the item in the Finder and choose File > Get Info.

I tracked it down, and the error is bubbling up from Disk+InternalHelpers.swift::188. That line calls createDirectory(at:withIntermediateDirectories:attributes:), which is throwing the error. The really weird thing is that "PDF" is supposed to be a subfolder of "Inbox", not a file inside it.

Here's the value for the subfolderUrl variable:
file:///var/mobile/Containers/Data/Application/AC2C2E56-8188-426A-8C59-E508B56C7954/Documents/Inbox/PDF/

Am I doing something wrong here? Why would this work in the simulator, but throw on a device?

Are you able to use Disk on your device in other scenarios? Are you sure title is a valid file name? If it is zero characters long or is in any other way invalid (see getValidFilePath in Disk+InternalHelpers.swift), then that may be the reason Disk is trying to save your object as a file named "PDF".

Yes, I use Disk all over the app (thank you btw), and title is most definitely valid. I even paused the debugger in getValidFilePath(from:) to double check, and it is not throwing an error.

I use the exact same code with the exact same test files in the simulator, and it works perfectly every time.

Turns out I was unaware that Apple reserves Documents/Inbox, and doesn't let you write to it.

From the documentation:

Your app can read and delete files in this directory but cannot create new files or write to existing files. If the user tries to edit a file in this directory, your app must silently move it out of the directory before making any changes.

When I changed the path to let path = "PDF/\(title)" everything works as expected.

Sorry for the trouble, but thank you for taking the time, and for making a great framework!