Last active
September 28, 2023 08:40
-
-
Save shaps80/edd48a625d06939cd8743946bd543448 to your computer and use it in GitHub Desktop.
URL with scoped security access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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