How to download PDF and store it locally on iPhone?

前端 未结 7 1320
时光说笑
时光说笑 2020-11-30 19:51

I am able to successfully view a PDF from a website. I want to be able to download that PDF to the device, then access that file locally.

When the app is opened, it

7条回答
  •  生来不讨喜
    2020-11-30 20:39

    Downloading and displaying PDF in Webview using Swift.

    let request = URLRequest(url:  URL(string: "http://www.msy.com.au/Parts/PARTS.pdf")!)
    let config = URLSessionConfiguration.default
    let session =  URLSession(configuration: config)
    let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
        if error == nil{
            if let pdfData = data {
                let pathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("\(filename).pdf")
                do {
                    try pdfData.write(to: pathURL, options: .atomic)
                }catch{
                    print("Error while writting")
                }
    
                DispatchQueue.main.async {
                    self.webView.delegate = self
                    self.webView.scalesPageToFit = true
                    self.webView.loadRequest(URLRequest(url: pathURL))
                }
            }
        }else{
            print(error?.localizedDescription ?? "")
        }
    }); task.resume()
    

提交回复
热议问题