Download PDF and save to the "Files" in iPhone, not to the app data, Swift

19,265

Here's how to download any files and save to Photos(if image file) or Files (if pdf)

let urlString = "your file url"
let url = URL(string: urlString)
let fileName = String((url!.lastPathComponent)) as NSString
// Create destination URL
let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
//Create URL to the source file you want to download
let fileURL = URL(string: urlString)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
    if let tempLocalUrl = tempLocalUrl, error == nil {
        // Success
        if let statusCode = (response as? HTTPURLResponse)?.statusCode {
            print("Successfully downloaded. Status code: \(statusCode)")
        }
        do {
            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            do {
                //Show UIActivityViewController to save the downloaded file
                let contents  = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
                for indexx in 0..<contents.count {
                    if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
                        let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
                        self.present(activityViewController, animated: true, completion: nil)
                    }
                }
            }
            catch (let err) {
                print("error: \(err)")
            }
        } catch (let writeError) {
            print("Error creating a file \(destinationFileUrl) : \(writeError)")
        }
    } else {
        print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "")")
    }
}
task.resume()
Share:
19,265
Rashid KC
Author by

Rashid KC

Coder

Updated on August 04, 2022

Comments

  • Rashid KC
    Rashid KC over 1 year

    I tried downloading pdf files with the below code. Here it's storing in the app data. But I need to show the downloaded pdf in "Files" folder in iPhone.

        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
    
        //Create URL to the source file you want to download
        let fileURL = URL(string: "http://swift-lang.org/guides/tutorial.pdf")
    
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
    
        let request = URLRequest(url:fileURL!)
    
        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }
    
                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }
    
            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
            }
        }
        task.resume()
    

    Is it possible??

    • Nikunj Kumbhani
      Nikunj Kumbhani over 5 years
      No, it's Not Possible to Save in iPhone you only store in App Data or either upload on iCloud.
    • Fabian
      Fabian over 5 years
      @NikunjKumbhani So the user can’t choose a place where he wants to save his files?
    • Nikunj Kumbhani
      Nikunj Kumbhani over 5 years
      @Purpose You can get the confirmation alert from a user before uploading in iCloud and then you can do it. For display this file you can use DocumentViwer.
    • Fabian
      Fabian over 5 years
      I’d like to learn more @NikunjKumbhani . Can you provide a link to learn this please?
    • Rashid KC
      Rashid KC over 5 years
      @NikunjKumbhani can I get the pdf data from above code?
    • Nikunj Kumbhani
      Nikunj Kumbhani over 5 years
      stackoverflow.com/a/42370660/10150796 Try this one for Document Pick from any resource as per your Requirement and for Display Purpose you can do it by just passing the Server URL to QLPreviewingController.
    • Fabian
      Fabian over 5 years
      @NikunjKumbhani Thank you that was very informative. Sharing to the built-in Files app would work though, right?