FireUser FireUser - 3 months ago 94
Swift Question

How to open file in swift?

I'm trying to open a

.pdf
file after download which is downloaded with Alamofire. But I've seen only using a "webview". Thus the application consumes lots of memory and is not viable.

What I want is to open it with the native device application. Any suggestions? Thank you.

Edit: This is my code for download file:

var localPath: NSURL?

Alamofire.download(.GET, url, destination: { (temporaryURL, response) in
let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pathComponent = response.suggestedFilename
localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)
return localPath!
})
.response { (request, response, _, error) in

if error != nil
{
// got an error in getting the data, need to handle it
print("Error: \(error!)")

}

//print(response)
print("Download file en:\(localPath!)")

self.view.hideToastActivity()
//self.actioncall()

}

}


I need open file from localpath...

Answer

You should use UIDocumentInteractionController. You can read about it on this Apple documentation page.

By doing some Googling you should see even some example implementations. For example here you can see some code about this done by "mattneub".

I let you one more code that you can use:

var documentInteractionController: UIDocumentInteractionController!

@IBAction func openDocument(sender: UIButton) {
  let URL: NSURL = NSBundle.mainBundle().URLForResource("yourPDF", withExtension: "pdf")!

    if (URL != "") {
        // Initialize Document Interaction Controller
        self.documentInteractionController = UIDocumentInteractionController(URL: URL)

        // Configure Document Interaction Controller
        self.documentInteractionController.delegate = self

        // Present Open In Menu
        self.documentInteractionController.presentOptionsMenuFromRect(sender.frame, inView: self.view, animated: true)
            //presentOpenInMenuFromRect
    }
}

// UIDocumentInteractionControllerDelegate
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
    return self
}
Comments