【问题标题】:share pdf file using UIActivityViewController in Swift 4在 Swift 4 中使用 UIActivityViewController 共享 pdf 文件
【发布时间】:2019-01-31 11:49:52
【问题描述】:

我正在使用 UIActivityViewController 来共享一个 PDF 文件:

let pdfFilePath = URL(string: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf")
let pdfData = NSData(contentsOf: pdfFilePath!)
let activityVC = UIActivityViewController(activityItems: [pdfData!], applicationActivities: nil)

present(activityVC, animated: true, completion: nil)

显示如下结果:

我想要显示更多功能,例如“复制到书籍”和“添加到笔记”,如下所示:

【问题讨论】:

  • 尝试将pdfFilePath而不是pdfData传递给活动视图控制器。
  • 我试过了,但是id不行

标签: ios swift uiactivityviewcontroller


【解决方案1】:

如果您想共享服务器上的 pdf 文件并且您有一个 URL。然后首先将该文件下载到您的设备中,然后将该文件共享给任何其他人。

如果您在代码中使用Alamofire,则有代码。

第一阶段

import Alamofire

第二阶段

在你的类中添加这个函数:-

func downloadPdf(downloadUrl : String, fileName: String, completionHandler:@escaping(String, Bool)->()){

        let destinationPath: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
            let fileURL = documentsURL.appendingPathComponent("\(fileName).pdf")
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        print(downloadUrl)
        Alamofire.download(downloadUrl, to: destinationPath)
            .downloadProgress { progress in

            }
            .responseData { response in
                print("response: \(response)")
                switch response.result{
                case .success:
                    if response.destinationURL != nil, let filePath = response.destinationURL?.absoluteString {
                        completionHandler(filePath, true)
                    }
                    break
                case .failure:
                    completionHandler("", false)
                    break
                }
        }
    }

第三阶段

在您的分享按钮上添加此操作

@IBAction func btnShareAction(_ sender: UIButton) {

        let myURL = "http://www.demo.com/demo.pdf"  // change this with your URL
        self.downloadPdf(downloadUrl : myURL, fileName: "invoice") { (localFileUrl, bool) in

             let fileURL = NSURL(fileURLWithPath: localFileUrl)
            let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
            self.present(activityViewController, animated: true, completion: nil)

          }
      }

【讨论】:

  • 嗨,当活动控制器打开默认邮件应用程序并且它没有在其中附加 pdf 时,我遇到了问题。它也适用于 gmail 应用程序和 Outlook。请提供建议。我真的坚持下去了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多