Code to read from iCloud Drive works on Mac Catalyst and iOS Simulator, gives permission errors on physical iOS device - Why?

The code here works on Mac Catalyst, and on the iOS simulator; on a physical iOS device it throws an error on the try Data line with an error, NSCocoaErrorDomain Cocoa=257: "The file couldn't be opened because you don't have permission to view it."

    let puzzleParser = PuzzleParser()
    var pseudoPuzzleData: Data
    let urlToLoad = UserDefaults.standard.url(forKey: "lastSavedDocument")          
    if urlToLoad != nil {
        let decoder = JSONDecoder()
        do {
            let result = urlToLoad?.startAccessingSecurityScopedResource()
            print("hello from loadInitialPuzzle(), \(result)")
            pseudoPuzzleData = try Data(contentsOf: urlToLoad!)
            urlToLoad?.stopAccessingSecurityScopedResource()
            AppDelegate.puzzle = try decoder.decode(Puzzle.self, from: pseudoPuzzleData)
       } catch // etc.

Any ideas why this is happening, and what to do about it? I could really use some help here ...

Replies

You probably need to save bookmark data instead of a path for the code to work on both platforms. See this function for more info. On the Mac, you might have to add the com.apple.security.files.bookmarks.app-scope=YES or com.apple.security.files.bookmarks.document-scope=YES entitlement when you do this. See this document for more info.