Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an iCloud Drive security scoped URL on iOS (UIDocumentPickerViewController)

Tags:

ios

cocoa

icloud

I'm trying to save the security scoped URL returned from iCloud document picker (UIDocumentPickerViewController)

The documentation states:

If the URL is not a ubiquitous URL, save a bookmark to the file using the bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error: method and passing in the NSURLBookmarkCreationWithSecurityScope option. Calling this method creates a bookmark containing a security-scoped URL that you can use to open the file without further user intervention.

However, the compiler says that NSURLBookmarkCreationWithSecurityScope is not supported on iOS.

Anyone know what's going on here....?

like image 623
Scotty Avatar asked Sep 18 '25 18:09

Scotty


2 Answers

After further digging, it turns out option NSURLBookmarkCreationWithSecurityScope is NOT needed at all when creating bookmark data in IOS. It's an option for OS X. You can just pass nil for the option field. I think Apple's document is confusing at the best.
However, you do need to call startAccessingSecurityScopedResource before creating the bookmark and make sure the call returns 1 (success) before proceed. Otherwise, bookmark creation will fail. Here is the sample code:

 if ([url startAccessingSecurityScopedResource]==1) {  
     NSError *error;  
     NSData *bookmark = [url bookmarkDataWithOptions:nil  
                      includingResourceValuesForKeys:nil  
                                       relativeToURL:nil  
                                               error:&error];  
     if (error) {
        //handle error condition  
     } else {
        // save your bookmark  
     }
 }  
 [url stopAccessingSecurityScopedResource];

Again Apple's document is confusion at the best! It took me a lot of time to find out this. Hope this helps.

like image 159
us_david Avatar answered Sep 20 '25 09:09

us_david


I ran into the same issue today, and indeed the compiler says NSURLBookmarkCreationWithSecurityScope is not available on iOS.

But to my surprise, if I use the raw constant instead (NSURLBookmarkCreationWithSecurityScope maps to ( 1 << 11 ), the method seems to work. It returns a valid bookmark data object, and when I call [[NSURL URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:stale], a valid security-scoped NSURL is returned and I can access the files and directories. Also, I tested these with iCloud Drive. And the documentation only says this should work for third-party document providers.

I am not sure how reliable this approach is, because it seems that Apple engineers didn't have time to finish up this feature, so disabled it in the last minute. Or it could be simply a bug in the header file. If anyone finds out more about this, please comment.

like image 25
ylian Avatar answered Sep 20 '25 08:09

ylian