Search code examples
cocoasandbox

dictionaryWithContentsOfFile and Sandbox


I've created a mac app that load a xml file from an user selected folder, and after using the app, the user saves a customized file (.adgf) When i try to load the .adgf file (that is a plist file) that has the xml path within one record i call dictionaryWithContentsOfFile but it return me a "nil". I think the problem is the sandbox (sometime it works sometime not). The string path is correct. Maybe when the user load the xml file should i save within of particular app "Document folder"?

Edit: I'm trying right now the Bookmark Data solution and I retraive a NSURL but it doen't work. The code I'm using is this:

- (NSData *)bookmarkFromURL:(NSURL *)url {
NSError *error = nil;
NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
                 includingResourceValuesForKeys:NULL
                                  relativeToURL:NULL
                                          error:&error];
if (error) {
    NSLog(@"Error creating bookmark for URL (%@): %@", url, error);
    [NSApp presentError:error];
}

return bookmark;
}

- (NSURL *)urlFromBookmark:(NSData *)bookmark {
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark
                                       options:NSURLBookmarkResolutionWithSecurityScope
                                 relativeToURL:NULL
                           bookmarkDataIsStale:NO
                                         error:NULL];
return url;
}

Solution

  • After the user stores the file you should take the bookmark data from the URL using -[NSURL bookmarkDataWithOptions: includingResourceValuesForKeys: relativeToURL: error:]

    Use NSURLBookmarkCreationWithSecurityScope for the options.

    This NSData object should be stored somewhere (plist?) and when you want to read the file again in a later session you can create a sandbox compliant NSURL from the bookmark data using +[NSURL URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:]