TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

"Error" using FileImporter and FileExporter

Forums > SwiftUI

@Pigna  

Every time I close the "File" modal to import or export a file, using the fileImporter and fileExporter modifier, I get this error/warning

[DocumentManager] The view service did terminate with error: Error Domain=_UIViewServiceErrorDomain Code=1 "(null)" UserInfo={Terminated=disconnect method}

Do you know hot to fix it?

1      

@Yury  

I also get that error message and I could not read the selected file. What sovled my issue was to call startAccessingSecurityScopedResource and then copy file to a temporary folder. Once file is copied it can be used with no issues. The error message is still there but at least I can access the file.

The code is ugly, so please do your housekeeping.

 .fileImporter(
            isPresented: $showImageFilePicker,
            allowedContentTypes: [.image],
            allowsMultipleSelection: false
        ) { result in
            do {
                guard let selectedFile: URL = try result.get().first else { return }

                guard selectedFile.startAccessingSecurityScopedResource() else {
                    // Handle the failure here.
                    return
                }

                let documentsUrl =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
                let destinationUrl = documentsUrl.appendingPathComponent(selectedFile.lastPathComponent)

                if let dataFromURL = NSData(contentsOf: selectedFile) {
                    if dataFromURL.write(to: destinationUrl, atomically: true) {
                        print("file saved [\(destinationUrl.path)]")
                        selectedImageURL = destinationUrl
                    } else {
                        print("error saving file")
                        let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                    }
                }

                selectedFile.stopAccessingSecurityScopedResource()

            } catch {
                print(error)
            }
        }

1      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.