如果您想共享服务器上的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"
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)
}
}
pdfData
替换为pdfFilePath
传递给活动视图控制器。 - rmaddy