@@ -69,26 +69,29 @@ struct AliasItem: Identifiable, Codable, Hashable {
6969 do {
7070 let url = try URL ( resolvingBookmarkData: bookmarkData, options: . withSecurityScope, relativeTo: nil , bookmarkDataIsStale: & isStale)
7171 if isStale {
72+ // If the bookmark is stale, we need to create a new one
7273 _ = try url. bookmarkData ( options: [ . withSecurityScope, . securityScopeAllowOnlyReadAccess] , includingResourceValuesForKeys: nil , relativeTo: nil )
74+ if let aliasItem = try ? AliasItem ( id: id, url: url) {
75+ return aliasItem. resolveURL ( )
76+ }
77+ }
78+ if !url. startAccessingSecurityScopedResource ( ) {
79+ print ( " Failed to access security scoped resource " )
80+ return nil
7381 }
7482 return url
7583 } catch {
76- print ( " StaplerApp: Alias: Error resolving bookmark: \( error) " )
84+ print ( " Error resolving bookmark: \( error) " )
7785 return nil
7886 }
7987 }
80-
81- static func == ( lhs: AliasItem , rhs: AliasItem ) -> Bool {
82- lhs. id == rhs. id && lhs. bookmarkData == rhs. bookmarkData
83- }
8488}
8589
8690struct StaplerDocument : FileDocument , Equatable {
8791 static var readableContentTypes : [ UTType ] { [ . staplerDocument] }
8892 static var writableContentTypes : [ UTType ] { [ . staplerDocument] }
8993
9094 var fileURL : URL ?
91-
9295 var aliases : [ AliasItem ]
9396
9497 init ( ) {
@@ -109,6 +112,7 @@ struct StaplerDocument: FileDocument, Equatable {
109112 let data = try Data ( contentsOf: url)
110113 let decodedData = try JSONDecoder ( ) . decode ( StaplerDocumentData . self, from: data)
111114 self . aliases = decodedData. aliases
115+ self . fileURL = url
112116 }
113117
114118 func fileWrapper( configuration: WriteConfiguration ) throws -> FileWrapper {
@@ -381,6 +385,10 @@ struct ContentView: View {
381385
382386 private func launchAlias( _ alias: AliasItem ) {
383387 if let url = alias. resolveURL ( ) {
388+ defer {
389+ url. stopAccessingSecurityScopedResource ( )
390+ }
391+
384392 let coordinator = NSFileCoordinator ( )
385393 var error : NSError ?
386394 coordinator. coordinate ( readingItemAt: url, options: . withoutChanges, error: & error) { url in
@@ -522,6 +530,15 @@ struct StaplerApp: App {
522530 // Launch all items and close the document
523531 DispatchQueue . main. async {
524532 do {
533+ // Start accessing the security-scoped resource
534+ guard url. startAccessingSecurityScopedResource ( ) else {
535+ logger. error ( " Failed to access security-scoped resource " )
536+ return
537+ }
538+ defer {
539+ url. stopAccessingSecurityScopedResource ( )
540+ }
541+
525542 let document = try StaplerDocument ( contentsOf: url)
526543 let viewModel = StaplerViewModel ( document: document)
527544 viewModel. launchAliases ( at: IndexSet ( integersIn: 0 ..< document. aliases. count) )
0 commit comments