1

I have url with pdf extension. On tapping the url, I want to show user with options to open URL with apps (which should include safari browser as well). I might achieve this by first downloading file from url in document directory and then open the file. But I don't want to download the file, rather I want to give user options to open that url. This is what I have tried for first downloading and then opening the file but even this is not showing up the options to pick the apps :

func openDocument(document: Document)
{
    let url = URL(string: document.documentUrl)
    var urlData = Data()
    do
    {
        urlData = try Data(contentsOf: url!)
    }
    catch
    {

    }

    if urlData != nil {
        var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let temp = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
       // let temp = NSURL(
        let targetPath = temp.appendingPathComponent("\("name").pdf")
        do
        {
            //try urlData.write(to: URL(fileURLWithPath: targetPath), options: .atomic)
            try urlData.write(to: targetPath, options: .atomic)
        }
        catch let error as NSError {
            print("Could not write file", error.localizedDescription)
        }
    }

    var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let temp = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
    let targetPath = temp.appendingPathComponent("\("name").pdf")
    let pdfUrl = URL(fileURLWithPath: targetPath.absoluteString)
    if pdfUrl != nil {
        documentInteractionController = UIDocumentInteractionController(url: pdfUrl)
        documentInteractionController.name = document.documentName
        documentInteractionController.delegate = self
        documentInteractionController.presentPreview(animated: true)
    }
}
Nitish
  • 13,845
  • 28
  • 135
  • 263
  • Using absoluteString to convert a URL to a file path is *wrong.* Compare http://stackoverflow.com/questions/39310200/can-not-save-file-inside-tmp-directory. – Martin R Mar 15 '17 at 12:20
  • @MartinR : I have updated my function but I am getting this : Couldn't issue file extension for path: /file:/private/var/mobile/Containers/Data/Application/80D26AB2-12BD-4631-90EE-A089C0943C46/tmp/name.pdf – Nitish Mar 15 '17 at 13:32
  • @MartinR : And the pdf keeps on loading – Nitish Mar 15 '17 at 13:33

0 Answers0