Fix security-scoped URL access balancing

This commit is contained in:
世界
2026-02-04 22:32:02 +08:00
parent 20e22b691a
commit 4ae421cd04
8 changed files with 77 additions and 32 deletions
@@ -24,9 +24,9 @@ public struct HTTPProxyCard: View {
Spacer()
Toggle("", isOn: $systemProxyEnabled)
.labelsHidden()
#if os(macOS)
.toggleStyle(.switch)
#endif
#if os(macOS)
.toggleStyle(.switch)
#endif
.onChangeCompat(of: systemProxyEnabled) { newValue in
Task {
await onToggle(newValue)
@@ -201,10 +201,11 @@ public struct NewProfileMenuView: View {
let fileName = url.deletingPathExtension().lastPathComponent
localImportRequest = NewProfileView.LocalImportRequest(name: fileName, fileURL: url)
} else {
_ = url.startAccessingSecurityScopedResource()
defer { url.stopAccessingSecurityScopedResource() }
let content = try LibboxProfileContent.from(Data(contentsOf: url))
let content = try url.withRequiredSecurityScopedAccess(
or: NSError(domain: "NewProfileMenuView", code: 0, userInfo: [NSLocalizedDescriptionKey: String(localized: "Missing access to selected file")])
) {
try LibboxProfileContent.from(Data(contentsOf: url))
}
alert = AlertState(
title: String(localized: "Import Profile"),
@@ -113,13 +113,11 @@ public final class NewProfileViewModel: BaseViewModel {
guard let fileURL else {
throw NSError(domain: "NewProfileViewModel", code: 0, userInfo: [NSLocalizedDescriptionKey: String(localized: "Missing file")])
}
if !fileURL.startAccessingSecurityScopedResource() {
throw NSError(domain: "NewProfileViewModel", code: 0, userInfo: [NSLocalizedDescriptionKey: String(localized: "Missing access to selected file")])
try fileURL.withRequiredSecurityScopedAccess(
or: NSError(domain: "NewProfileViewModel", code: 0, userInfo: [NSLocalizedDescriptionKey: String(localized: "Missing access to selected file")])
) {
try String(contentsOf: fileURL).write(to: profileConfig, atomically: true, encoding: .utf8)
}
defer {
fileURL.stopAccessingSecurityScopedResource()
}
try String(contentsOf: fileURL).write(to: profileConfig, atomically: true, encoding: .utf8)
} else {
try "{}".write(to: profileConfig, atomically: true, encoding: .utf8)
}
@@ -129,10 +127,6 @@ public final class NewProfileViewModel: BaseViewModel {
try FileManager.default.createDirectory(at: FilePath.iCloudDirectory, withIntermediateDirectories: true)
}
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(remotePath, isDirectory: false)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
do {
_ = try String(contentsOf: saveURL)
} catch {