2

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.

LittleFunny
  • 8,155
  • 15
  • 87
  • 198

1 Answers1

2

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

Community
  • 1
  • 1
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • What happened with two device accessing the file and both of them modified the same file e.g. One added a string of "Me" and the other remove "A" will there be a problem. – LittleFunny Sep 29 '16 at 02:14
  • @Simon Two devices? Are you talking about a "cloud"-based resource being modified by two different devices at the same time? And which cloud service? – SushiHangover Sep 29 '16 at 02:16
  • sorry i am very new to this.. Yea the file in the cloud – LittleFunny Sep 29 '16 at 02:23
  • Which cloud service? – SushiHangover Sep 29 '16 at 02:24
  • "For iOS apps, if you use a UIDocument to access the URL, it automatically manages the security-scoped URL for you." Oh thanks lord I had missed this important sentence. – Warpzit Oct 26 '20 at 10:22