Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Permission error when saving to documentDirectory

I am trying to save favourites to document directory, the code works fine when I run it in simulator however when I build it to my device I am getting the following error.

You don’t have permission to save the file
“Documents.LikedDepartments” in the folder
“F36073C0-AC1E-46CA-BC1E-E03F9F316E1D”.

Also it might be worth noting that when I change use .cachesDirectory instead of .documentDirectory it works fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I grant write access for the documents directory ?

import Foundation

extension FileManager {
    static var documentsDirectory: URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        print(paths)
        return paths[0]
    }
}
let savePath = FileManager.documentsDirectory.appendingPathExtension("LikedDepartments")

func save() {
    let favourites = calculateFavourites()
    do {
        let data = try JSONEncoder().encode(favourites)
        try data.write(to:savePath, options: [.atomic, .completeFileProtection])
    } catch {
        print("\(error)")
    }
}

>Solution :

Cool file extension .LikedDepartments

Use appendingPathComponent instead.

https://developer.apple.com/documentation/foundation/nsstring/1417069-appendingpathcomponent

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading