How to save a file in Files iOS system app in iOS 17 Swift

57 views Asked by At

Since iOS 17, I can't find a way to save a file (.pdf, .mp3, .m4a, etc.) in the "Files" iOS system app in Swift. I am using Xcode 15.2.

In iOS 15 and iOS 16, here is my code and it works on the last iOS.

func saveFile(_ name: String, fileExtension: String, url: URL, progressHandler: ((Float) -> Void)? = nil, completionHandler: ((Error?) -> Void)? = nil) {
        let fileURL = getDirectory().appendingPathComponent("\(name).\(fileExtension)")
        let downloadTask = URLSession.shared.downloadTask(with: url) { (tempURL, response, error) in
            if let error = error {
                completionHandler?(error)
                return
            }
            
            guard let tempURL = tempURL else {
                completionHandler?(NSError(domain: "Download error", code: 0, userInfo: nil))
                return
            }
            
            do {
                let isFileFound: Bool? = FileManager.default.fileExists(atPath: fileURL.path)
                
                if isFileFound == true {
                    print("File already exists: \(fileURL)")
                } else {
                    try FileManager.default.moveItem(at: tempURL, to: fileURL)
                    print("fileURL: \(fileURL)")
                }
                completionHandler?(nil)
            } catch {
                completionHandler?(error)
            }
        }
        
        let progressObserver = downloadTask.progress.observe(\.fractionCompleted, options: [.new]) { progress, _ in
            progressHandler?(Float(progress.fractionCompleted))
        }
        
        downloadTask.resume()
}

func getDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectory = paths[0]
        return documentDirectory
}

This code on iOS17 produce no error and no crash, it seems system successfully download the file and save it in Files app but I cannot find the file anywhere. There is no message in the Xcode console. In iOS15 and 16, this code create a folder with my app name in the Files app and the downloaded file is saved in this folder and I can open it.

Here is the file url looks like in iOS17 : file:///var/mobile/Containers/Data/Application/98BB1C5F-BB8F-4768-B38C-9724E4142ED7/Documents/filename.m4a for example

I know there was some changes in File system in iOS17, the system has reorganized where applications and their data containers are stored. So maybe the file is successfully save in Files app but where, or maybe it is somewhere else in the device ? Or maybe I need some permissions now ?

If someone can help me with this issue.

0

There are 0 answers