Skip to content

Instantly share code, notes, and snippets.

@shaps80
Last active September 28, 2023 08:40
Show Gist options
  • Save shaps80/edd48a625d06939cd8743946bd543448 to your computer and use it in GitHub Desktop.
Save shaps80/edd48a625d06939cd8743946bd543448 to your computer and use it in GitHub Desktop.
URL with scoped security access
import Foundation
struct ScopeError: LocalizedError {
let url: URL
var errorDescription: String? {
"Unabled to gain scoped access to the url: \(url)"
}
}
extension URL {
func withScopedAccess<T>(_ closure: (URL) async throws -> T) async throws -> T {
let isScoped = startAccessingSecurityScopedResource()
guard isScoped else { throw ScopeError(url: self) }
defer { stopAccessingSecurityScopedResource() }
return try await closure(self)
}
func withScopedAccess<T>(_ closure: (URL) throws -> T) throws -> T {
let isScoped = startAccessingSecurityScopedResource()
guard isScoped else { throw ScopeError(url: self) }
defer { stopAccessingSecurityScopedResource() }
return try closure(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment