使用 swift 代码将 web 视图上的 pdf 共享到其他设备
Posted
技术标签:
【中文标题】使用 swift 代码将 web 视图上的 pdf 共享到其他设备【英文标题】:Share pdf on web view to another devices using swift code 【发布时间】:2019-05-13 00:04:24 【问题描述】:我有一个显示 pdf 的 WKWebView。我想将文件共享到其他设备,例如 iPad、iPhone.... 使用共享按钮。我尝试在预览中显示 pdf,这样它就会有 ios 共享按钮,下面的代码。
import UIKit
import WebKit
class ShowPDFView: UIViewController, UIDocumentInteractionControllerDelegate
@IBAction func SharePDFFile(_ sender: Any)
let fileName = "testPDF"
guard let urlPath = Bundle.main.url(forResource: fileName, withExtension: "pdf") else return
let controller = UIDocumentInteractionController(url: urlPath)
controller.delegate = self
controller.presentPreview(animated: true)
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController!) -> UIViewController!
return self
func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController!) -> UIView!
return self.view
func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController!) -> CGRect
return self.view.frame
我遇到了运行时错误。
[MC] Reading from private effective user settings.
预览未加载。有谁知道为什么?
【问题讨论】:
【参考方案1】:这个功能对我有用。在 Swift 4 中
@IBAction func SharePDFFile(_ sender: Any)
let fm = FileManager.default
var pdfURL = (fm.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent("johnMilky.pdf") as URL
//Rename document name to "myFile.pdf"
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("johnMilkyFile.pdf") as NSURL
do
let data = try Data(contentsOf: pdfURL)
try data.write(to: url as URL)
let activitycontroller = UIActivityViewController(activityItems: [url], applicationActivities: nil)
if activitycontroller.responds(to: #selector(getter: activitycontroller.completionWithItemsHandler))
activitycontroller.completionWithItemsHandler = (type, isCompleted, items, error) in
if isCompleted
print("completed")
//activitycontroller.excludedActivityTypes = [UIActivity.ActivityType.airDrop]
activitycontroller.popoverPresentationController?.sourceView = self.view
self.present(activitycontroller, animated: true, completion: nil)
catch
print(error)
【讨论】:
以上是关于使用 swift 代码将 web 视图上的 pdf 共享到其他设备的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Web 视图打开 Safari 视图控制器(swift)
无法在 swift WebView 中加载/滚动完整的 pdf。