Permission error when saving to documentDirectory

84 Views Asked by At

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.

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)")
    }
}
1

There are 1 best solutions below

2
Warren Burton On BEST ANSWER

Cool file extension .LikedDepartments

Use appendingPathComponent instead.

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