无法在 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
})
}
}
}

检查我的简单代码可能对您有所帮助,并且不要忘记为 whatsapp 配置共享设置,因为它只会出现在共享实例中。

@objc func shareTapped() {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: documentPath!))
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [docTitle!,data], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
print("pdf file loading...")
}
catch {
let msgView = Utils.swiftMeassageView(title: "", message: "PDF file not found.", theme: .info)
SwiftMessages.show(view: msgView)
}
}

Info.plist中添加这两个键:

  • 文件共享已启用,UIFileSharingEnabled:此键(应用程序支持iTunes文件共享(将启用iTunes共享"文档"文件夹中的文件。确保将布尔值设置为 true。
  • LSSupportsOpeningDocumentsInPlace:此密钥(支持就地打开文档(将授予对应用程序文件提供程序的访问权限,以读取或写入文档文件夹中的文件。请确保将布尔值设置为"是"。
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")
}

最新更新