在Swift 4中使用UIActivityViewController分享PDF文件

6

我正在使用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)

以下结果显示:

输入图像描述

我想要的是像下面这样显示更多功能,如“复制到书籍”和“添加到笔记”:

输入图像描述


1
尝试将pdfData替换为pdfFilePath传递给活动视图控制器。 - rmaddy
我尝试了,但它没有起作用。 - Fatima
2个回答

3

如果您想共享服务器上的PDF文件并且拥有URL,则首先需要下载该文件到您的设备,然后将该文件分享给其他人。

如果您在代码中使用Alamofire,则可以使用以下代码。

步骤1

import Alamofire

步骤 2

在你的类中添加以下函数:

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)

          }
      }

1
嗨,当活动控制器打开默认邮件应用程序时,我遇到了问题,它无法附加PDF文件。对于Gmail应用程序和Outlook也可以正常工作。请提供建议。我真的被卡住了。 - iAmita Singh

-1

简单的步骤!复制粘贴给定的代码

@objc private func btnShareTapped(_ sender: UIButton) {
    guard let urlString = strURL,
          let url = URL(string: urlString),
          let docPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
        return
    }
    let actualPath = docPath.appendingPathComponent("Statement.pdf")
    let pdfData = try? Data.init(contentsOf: url)

    do {
        try pdfData?.write(to: actualPath, options: .atomic)
        let fileURL = URL(fileURLWithPath: actualPath.absoluteString)
        let activityVC = UIActivityViewController(activityItems: [fileURL],
                                                  applicationActivities: nil)
        present(activityVC, animated: true)
    } catch {
        debugPrint("Pdf could not be saved")
    }
}

1
这将在上传期间冻结您的用户界面。 - Sulthan
我尝试了一下,没有冻结。你那边会冻结吗?也许我们需要添加加载指示器来处理大的PDF文件。 - Yano
在主线程上调用Data.init(contentsOf: url)来初始化数据是概念上不正确的,特别是当这个URL是一个网络资源时。同样,在将数据写入大文件时,通过data.write(to: path)来复制文件也是不合适的。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接