swift - 无法快速分享 pdf(仅限 WhatsApp)
问题描述
我想从应用程序共享 pdf 文件。我收到一个错误“无法共享”文档一些 pdf。我在某些文件中没有收到错误。这是我的代码:
class DocumentURL: UIActivityItemProvider {
let temporaryURL: URL
let document: DocumentAndDemandForm
let data : Data
init(document: DocumentAndDemandForm,data:Data) {
self.document = document
self.data = data
self.temporaryURL = URL(fileURLWithPath: NSTemporaryDirectory() + "\(document.downloadName == "" ? document.description ?? "ek" : document.downloadName).pdf")
super.init(placeholderItem: temporaryURL)
}
override var item: Any {
get {
try? data.write(to: temporaryURL)
return temporaryURL
}
}
}
func share(isSave:Bool = false) {
if let data = pdfView.document?.dataRepresentation(){
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [DocumentURL.init(document: self.document, data: data)], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.pdfView
if isSave{
activityViewController.excludedActivityTypes = [.airDrop,.assignToContact,.copyToPasteboard,.mail,.message,.openInIBooks,.postToFacebook,.postToFlickr,.postToTencentWeibo,.postToTwitter,.postToVimeo,.postToWeibo]
}
DispatchQueue.main.async {
self.controller.present(activityViewController, animated: true, completion: {
self.shareDocument = false
})
}
}
}
解决方案
在你的添加这两个键Info.plist
:
- 启用文件共享,
UIFileSharingEnabled
:此键(应用程序支持 iTunes 文件共享)将启用 iTunes 共享您 Documents 文件夹中的文件。确保将布尔值设置为 true。 LSSupportsOpeningDocumentsInPlace
:此密钥(支持在适当位置打开文档)将授予应用程序文件提供者读取或写入 Documents 文件夹中文件的权限。确保将布尔值设置为 YES。
let fileManager = FileManager.default
let documentoPath = getDirectoryPath().appendingPathComponent(url.lastPathComponent) as URL
print("documentoPath :\(documentoPath)")
if fileManager.fileExists(atPath: documentoPath.path) {
DispatchQueue.main.async {
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [documentoPath], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.downloadNavController?.present(activityViewController, animated: true, completion: { () in
UIBarButtonItem.appearance().tintColor = UIColor.systemBlue
UINavigationBar.appearance().barTintColor = UIColor.white
})
}
} else {
print("document was not found")
}