Search code examples
swiftnsurlconnectionnsurlsessiondownloadtask

Issue facing in changing path directory for downloaded files in swift


Facing issue, while downloading PDF through API. Issues are follows:

  1. I can download PDF through my API link. Download completed. But its path is, /Users/***********/Library/Developer/CoreSimulator/Devices/58BD307-ED3A-4F34-9FCB-3391FDCC068D/data/Containers/Data/Application/DBB11FA91-2387-4124-9E07-2E92B22636B5/Documents/tfData. How can I change the path?

  2. I need to store downloaded PDF in core data and I need to display in my web view from core data. I couldn do that. Kindly guide me.

2.1 First, I dont know how to display downloaded PDF to my web view.

My Coding Part:

//FATAL ERROR RECEIVING
let filemanager = NSFileManager.defaultManager()

    let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]

    let destinationPath:NSString = documentsPath.stringByAppendingString("/tfData.pdf")

    println("destinationPath     \(destinationPath)")

    let pdf = NSURL(fileURLWithPath: destinationPath as String)

    println("destinationPath pdf    \(pdf)")

    let req = NSURLRequest(URL: pdf!)

    println("destinationPath req    \(req)")

    let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
    webView.loadRequest(req)
    self.view.addSubview(webView)
    //NOT DISPLAYING IN WEB VIEW. 

LOGS

destinationPath     /Users/***********/Library/Developer/CoreSimulator/Devices/58BD307-ED3A-4F34-9FCB-3391FDCC068D/data/Containers/Data/Application/DBB11FA91-2387-4124-9E07-2E92B22636B5/Documents/tfData.pdf
destinationPath pdf    Optional(file:///Users/***********/Library/Developer/CoreSimulator/Devices/58BD307-ED3A-4F34-9FCB-3391FDCC068D/data/Containers/Data/Application/DBB11FA91-2387-4124-9E07-2E92B22636B5/Documents/tfData.pdf)
destinationPath req    <NSURLRequest: 0x7f8083706330> { URL: file:///Users/***********/Library/Developer/CoreSimulator/Devices/58BD307-ED3A-4F34-9FCB-3391FDCC068D/data/Containers/Data/Application/DBB11FA91-2387-4124-9E07-2E92B22636B5/Documents/tfData.pdf }

Kindly guide me. How to solve this issues? I can do only 1st thing alone.

Why I am doing like this means, user can read pdf in OFFLINE mode too. So I need like this.


Solution

  • You can load PDF this way in your webView:

    if let pdf = NSBundle.mainBundle().URLForResource("yourPDFName", withExtension: "pdf", subdirectory: nil, localization: nil)  {
            let req = NSURLRequest(URL: pdf)
            let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
            webView.loadRequest(req)
            self.view.addSubview(webView)
     }