我需要在iOS下共享/打开一些不同的文件,例如,到iCloud的图像或到iBooks的pdf。文本和图像周围有几个示例,但其他方面则没有。
我创造了自己的UIActivityItemProvider; 简化版在这里:
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)
我期望像这样的共享对话:
但是我得到的是:
有什么建议?
**
我花了很多时间思考如何在从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") } }