swift – Modifying a file saved as bookmarkData in iOS SwiftUI


I am picking a dropbox file and saving it as a bookmark using bookmarkData in my iOS app. It works perfectly

 func addBookmark(for url: URL) {
        do {
            // Start accessing a security-scoped resource.
            guard url.startAccessingSecurityScopedResource() else {
                // Handle the failure here.
                return
            }
            
            // Make sure you release the security-scoped resource when you finish.
            defer { url.stopAccessingSecurityScopedResource() }
            
            // Convert URL to bookmark
            let bookmarkData = try url.bookmarkData(options: .minimalBookmark, includingResourceValuesForKeys: [ .contentModificationDateKey], relativeTo: nil)
            
            try bookmarkData.write(to: getAppSandboxDirectory().appendingPathComponent("filePath"))
            
            // Add the URL and UUID to the urls array
            withAnimation {
                urls.removeAll()
                urls.append(url)
            }
        }
        catch {
            // Handle the error here.
            print(error.localizedDescription)
        }
        
    }

Then I modify that file, for example add a new line to the text file in dropbox. File syncs to my device. (If I open it from files app I can see the modified data).

But when I resolve the bookmarked url and view it in my app, it shows old version of the file. Not the modified one with the new data.

func loadAllBookmarks() {
        // Get all the bookmark files
        let files = try? FileManager.default.contentsOfDirectory(at: getAppSandboxDirectory(), includingPropertiesForKeys: nil)
        // Map over the bookmark files
        self.urls = files?.compactMap { file in
            do {
                let bookmarkData = try Data(contentsOf: file)
                var isStale = false
                // Get the URL from each bookmark
                let url = try URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &isStale)
                
                
                guard !isStale else {
                    print("isStale")
                    // Handle stale data here.
                    return nil
                }
                // Return URL
                return url
            }
            catch let error {
                // Handle the error here.
                print("\(error)")
                return nil
            }
        } ?? []
    }

Edit: Also if I open the file picker from my app again it shows the cloud downloadable icon and it automatically downloads the file, without even choosing the file.

Then I closed the file picker and i could see the file was updated in my app too. But I want to do it without let the user choose the file again,

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img