Search code examples
iosswiftpdfpreview

How to download a Pdf file in swift and find in file manager


I have downloaded a pdf using code below. I am able to find the file in App Data Container, but from app data container my device needs Mac, x code or iTunes etc.

Can I give a distinction path to Documents OR another place to find the pdf in iPhone files? I have an option to open the file with iBook but it is not there.

My code to download the file is here:

func downloadFile(){
        let url = "https://www.tutorialspoint.com/swift/swift_tutorial.pdf"
        let fileName = "MyFile"
        
        savePdf(urlString: url, fileName: fileName)
      
    }

    func savePdf(urlString:String, fileName:String) {
            DispatchQueue.main.async {
                let url = URL(string: urlString)
                let pdfData = try? Data.init(contentsOf: url!)
                let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
                let pdfNameFromUrl = "YourAppName-\(fileName).pdf"
                let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl)
                do {
                    try pdfData?.write(to: actualPath, options: .atomic)
                    print("pdf successfully saved!")
    //file is downloaded in app data container, I can find file from x code > devices > MyApp > download Container >This container has the file
                } catch {
                    print("Pdf could not be saved")
                }
            }
        }

Solution

  • Configure your app so that its files appear in the Files app by adding below lines to your Info.plist file.

    <key>UIFileSharingEnabled</key>
    <true/>
    <key>LSSupportsOpeningDocumentsInPlace</key>
    <true/>
    

    OR

    Just like below using Xcode

    enter image description here

    Note: Remember that you must be running iOS 11 or above.