Я пытаюсь сохранить сеанс пользователя в своем приложении, и я немного прочитал об этой области безопасности файлового менеджера, но я действительно не понимаю, как она работает. / stopAccessingSecurityScopedResource?
// MARK: - Private
extension Storage {
private func store(_ session: Session, as name: String) throws {
let url = try getURL().appendingPathComponent(name, isDirectory: false)
guard url.startAccessingSecurityScopedResource() == true else {
throw PersistenceError.error("[Storage] Unable to access resource due to security scope.")
}
let data = try JSONEncoder().encode(session)
if FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.removeItem(at: url)
}
FileManager.default
.createFile(atPath: url.path, contents: data,
attributes: [.protectionKey: FileProtectionType.complete])
url.stopAccessingSecurityScopedResource()
}
private func retrieve(_ name: String) throws -> Session {
var session: Session!
let url = try getURL().appendingPathComponent(name, isDirectory: false)
if !FileManager.default.fileExists(atPath: url.path) {
throw PersistenceError.error("[Storage] No data at location: \(url.path)")
}
if !url.startAccessingSecurityScopedResource() {
throw PersistenceError.error("[Storage] Unable to access resource due to security scope.")
}
if let data = FileManager.default.contents(atPath: url.path) {
session = try JSONDecoder().decode(Session.self, from: data)
} else {
throw PersistenceError.error("[Storage] No data at location: \(url.path)")
}
url.stopAccessingSecurityScopedResource()
return session
}
private func getURL() throws -> URL {
guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
throw PersistenceError.error("[Storage] Could not create URL for specified directory")
}
return url
}
}