小编典典

使用UIActivityViewController和UIActivityItemProvider共享PDF

swift

我需要在iOS下共享/打开一些不同的文件,例如,到iCloud的图像或到iBooks的pdf。文本和图像周围有几个示例,但其他方面则没有。

我创造了自己的UIActivityItemProvider; 简化版在这里:

class MyItemProvider: UIActivityItemProvider {

  override func item() -> AnyObject {
    self.placeholderItem
  }

  override func activityViewController(activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: String?) -> String {
    return kUTTypePDF as String
  }

  func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
    return self.placeholderItem
  }
}

并开始与以下内容共享:

let myPDF = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("testpdf", withExtension: "pdf")) {
let activityVC = UIActivityViewController(activityItems: [MyItemProvider(placeHolder: myPDF)], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)

我期望像这样的共享对话:

在此处输入图片说明

但是我得到的是:

在此处输入图片说明

有什么建议?


阅读 405

收藏
2020-07-07

共1个答案

小编典典

**

在Swift 3中使用UIActivityViewController共享PDF

**

我花了很多时间思考如何在从URL加载的UIWebView中共享PDF文件,例如“
http://youPdfFile.pdf

经过几天的忙碌,我发现了我认为最合适的方法:

1)PDF必须首先保存在文件系统中。 例如,可以在加载UIWebView之后完成:

class yourViewController: UIViewController{
       var documentPathToLoad = "http://youPdfFile.pdf"
       ...

       func webViewDidFinishLoad(_ webView: UIWebView) { 
           if yourWebView.isLoading { 
               // still loading 
               return 
           }

           //Save the pdf document to file system 
           savePdf() 
       }

       func savePdf(){    
           let fileManager = FileManager.default 
           let paths = (NSSearchPathForDirectoriesInDomain((.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("documento.pdf") 
           let pdfDoc = NSData(contentsOf:URL(string: documentPathToLoad)!) 
           fileManager.createFile(atPath: paths as String, contents: pdfDoc as Data?, attributes: nil) 
       } 
}

2)读取保存的文件,然后共享。 此方法在Swift 3.0.1中对我有效:

func loadPDFAndShare(){

           let fileManager = FileManager.default 
           let documentoPath = (self.getDirectoryPath() as NSString).appendingPathComponent("documento.pdf")

           if fileManager.fileExists(atPath: documentoPath){              
                let documento = NSData(contentsOfFile: documentoPath) 
                let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [documento!], applicationActivities: nil) 
                activityViewController.popoverPresentationController?.sourceView=self.view 
                present(activityViewController, animated: true, completion: nil) 
            } 
            else { 
                print("document was not found") 
            } 
        }
2020-07-07