How to determine whether an NSURL has security scope info?

Viewed 319

In earlier versions of macOS, NSURL instances constructed from a security-scoped bookmark would have an ?applesecurityscope=... query string tagged onto the end of them. I was checking for this in a unit test, as it was a requirement of the function under test. Now, starting with 10.10 Yosemite, I can't find a way to determine from any public-facing property of an NSURL whether or not it has security scope.

There is no query or parameterStrings value, and -startAccessingSecurityScopedResource returns YES whether a URL has security scope or not.

This is especially useful to test for since my unit tests don't run in a sandboxed environment, but the app is, so the URLs the function produces must have security scope.

1 Answers

You can try to obtain a security scoped bookmark from that url. This only works if the url is already security scoped and will fail for "regular" urls:

let isSecurityScoped = (try? url.bookmarkData(options: .withSecurityScope,
                               includingResourceValuesForKeys: nil, 
                               relativeTo: nil)) != nil

Alternatively you can try calling url.startAccessingSecurityScopedResource(). This only succeeds if the url is security scoped.

Related