Xamarin iOS: Why required to call StartAccessingSecurityScopedResource and release it in the DocPicker Sample

368 Views Asked by At

I am using Document Picker in Xamarin iOS. In the sample of the DocPicker, they called something like StartAccessingSecurityScopedResource with comment on top.

// IMPORTANT! You must lock the security scope before you can // access this file.

Why do they have to lock this file? Is it prevent the file from modify from somewhere else while accessing the file.

1

There are 1 best solutions below

5
SushiHangover On

In iOS (and MacOS sandboxed apps), accessing an external document, a document that is outside of your own app's sandbox, requires special permission that is tracked by the OS. So once you have a NSUrl that points to an external file, you actually do not have access to it until you definitively ask for it as there is an security/resource overhead in doing so,

Note: Make sure that you call StopAccessingSecurityScopedResource otherwise your app leaks kernel-based resources (try/finally is a wise coding pattern here)

In iOS, apps that open or move documents using a UIDocumentPickerViewController also receive security-scoped URLs.

To gain access to a security-scoped URL, you must call the startAccessingSecurityScopedResource() method (or its Core Foundation equivalent, the CFURLStartAccessingSecurityScopedResource(_:) function). For iOS apps, if you use a UIDocument to access the URL, it automatically manages the security-scoped URL for you.

Ref: Security-Scoped URLs