2016-11-10 150 views
1

如何在顯示所有可以讀取pdf文件的應用程序(例如adobe pdf reader)時點擊按鈕?我搜索,但我發現,大多數使用UIWebView來顯示PDF文件。我如何用我描述的方式來做到這一點?Swift:將pdf文件讀入pdf應用程序讀取器

編輯: 我只有PDF鏈接,我從服務器獲取

+0

嘗試喲使用'UIDocumentInteractionController()' –

回答

0

試試這個

var docController:UIDocumentInteractionController! 
let pdfUrl = NSURL(string: "ENTER_URL_OF_PDF") 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    downloadDoc(pdfUrl: pdfUrl!) 
} 

@IBAction func buttonAction(_ sender: AnyObject) { 
    docController.presentOptionsMenu(from: self.view.frame, in: self.view, animated: true) 
} 

func downloadDoc(pdfUrl : NSURL) { 
    let urlTest = self.pdfUrl!.absoluteString 
    let pdfUrl = NSURL(string: urlTest!) 
    if(pdfUrl != nil){ 
     let pdfRequest: NSURLRequest = NSURLRequest(url: pdfUrl! as URL) 
     NSURLConnection.sendAsynchronousRequest(pdfRequest as URLRequest, queue: OperationQueue.main) {(response, data, error) in 
      let httpResponse = response as? HTTPURLResponse 
      if(httpResponse?.statusCode == 200 && error == nil){ 
       let documentsUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first as! NSURL 

       if let fileName = self.pdfUrl!.lastPathComponent { 
        let destinationUrl = documentsUrl.appendingPathComponent(fileName) 
        if let data = data { 
         do { 
          try data.write(to: destinationUrl!, options: .atomic) 
         } catch { 
          print(error) 
         } 
         self.docController = UIDocumentInteractionController(url: destinationUrl!) 
        } 
       } 

      } 

     } 

    } 

} 
+0

謝謝你的答案。如果我只有pdf網址怎麼辦? (從服務器獲取pdf鏈接)? –

+0

請參閱我的編輯 –

+0

編輯答案..現在檢查它。 – Binesh

0

您可以UIDocumentInteractionController去,它會處理所有你喜歡縮放PDF,滾動,顯示出合適的應用程序來處理pdf。

SWIFT 2.3:

import UIKit 

class ViewController:UIViewController, UIDocumentInteractionControllerDelegate { 

var documentController: UIDocumentInteractionController = UIDocumentInteractionController() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    downloadFileForfileObject("https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf") 
} 

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
} 

func downloadFileForfileObject(url: String) { //Download pdf File asynchronosly 
    let documentURL = NSURL(string: url) 
    let documentsURLPath = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL 

    let fileExtension = ((documentURL!.pathComponents)?.last)! as String 
    let request: NSURLRequest = NSURLRequest(URL: documentURL!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60) 
    let fileURLPath = documentsURLPath.URLByAppendingPathComponent("\(fileExtension)") 

    let sessionCobfig = NSURLSessionConfiguration() 
    let session = NSURLSession(configuration: sessionCobfig, delegate: nil, delegateQueue: nil) 
    let task = session.dataTaskWithRequest(request) { (data, response, error) in 
     if error == nil { 
      self.openSelectedDocumentFromURL((fileURLPath?.path!)!) 
     } else { 
      print(error?.localizedDescription) 
     } 
    } 
    task.resume() 
} 

func openSelectedDocumentFromURL(documentURLString: String) { 
    let documentURL: NSURL = NSURL(fileURLWithPath: documentURLString) 
    documentController = UIDocumentInteractionController(URL: documentURL) 
    documentController.delegate = self 
    documentController.presentPreviewAnimated(true) 
} 

// MARK: - UIDocumentInteractionViewController delegate methods 

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

}

呼叫downloadFileForfileObject()在viewDidLoad方法與PDF網址作爲參數。 PDF將通過UIDocumentInteractionController委託方法自動顯示。

SWIFT 3:

import UIKit 

class MOViewController:UIViewController, UIDocumentInteractionControllerDelegate { 

var documentController: UIDocumentInteractionController = UIDocumentInteractionController() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    downloadFileForfileObject(url: "https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf") 
} 

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

} 

func downloadFileForfileObject(url: String) { //Download pdf File asynchronosly 
    let documentURL = NSURL(string: url) 
    let documentsURLPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL 

    let fileExtension = ((documentURL!.pathComponents)?.last)! as String 
    let request: URLRequest = URLRequest(url: documentURL! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: 60) 
    let fileURLPath = documentsURLPath.appendingPathComponent("\(fileExtension)") 

    let sessionConfig = URLSessionConfiguration.default 
    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) 

    let teask = session.dataTask(with: request) { (data, response, error) in 
     if (error == nil) { 
      // Success 
      self.openSelectedDocumentFromURL(documentURLString: fileURLPath!.path) 
     } else { 
      print(error?.localizedDescription) 
     } 
    } 
    teask.resume() 
    } 

func openSelectedDocumentFromURL(documentURLString: String) { 
    let documentURL: NSURL = NSURL(fileURLWithPath: documentURLString) 
    documentController = UIDocumentInteractionController(url: documentURL as URL) 
    documentController.delegate = self 
    documentController.presentPreview(animated: true) 
} 


// MARK: - UIDocumentInteractionViewController delegate methods 

func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { 
    return self 
} 

文檔下載驗證: 您檢查文件是否是下載或不如下,看圖像。 enter image description here

輸出:

enter image description here

謝謝:)

+0

能否請你看看我的編輯?謝謝 –