与 UIActivityViewController 共享 PDF - 文件名
Posted
技术标签:
【中文标题】与 UIActivityViewController 共享 PDF - 文件名【英文标题】:Sharing PDF with UIActivityViewController - File Name 【发布时间】:2019-12-30 16:41:26 【问题描述】:我正在创建一个 PDF 并通过 UIActivityViewController
共享它。
func createFlyer() -> Data
// 1
let pdfMetaData = [
kCGPDFContextCreator: "Flyer",
]
let format = UIGraphicsPDFRendererFormat()
format.documentInfo = pdfMetaData as [String: Any]
// 2
let pageWidth = 8.5 * 72.0
let pageHeight = 11 * 72.0
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
// 3
let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
// 4
let data = renderer.pdfData (context) in
// 5
context.beginPage()
// 6
let attributes = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
]
let text = "I'm a PDF!"
text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
return data
func sharePDF ()
let activityViewController = UIActivityViewController(
activityItems: [data], applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivity.ActivityType.saveToCameraRoll]
if let popoverPresentationController = activityViewController.popoverPresentationController
popoverPresentationController.barButtonItem = self.sharePDFButton
self.present(activityViewController, animated: true, completion:
)
一切都很好,除了文件名是系统生成的('PDF Document.pdf')。
有没有办法自定义文件名?
【问题讨论】:
尚未对此进行测试,可能有更好的方法来完成此操作,但您可以尝试先将文件保存到临时文件夹。像这样:***.com/a/52467491/12555191 不是最方便的方法,但似乎可行。 【参考方案1】:在展示activityViewController时请尝试使用下面的代码,我希望它有效。
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
)
您可以在这里找到 getDirectoryPath():
func getDirectoryPath() -> URL
var nestedFolderURL: URL?
do
let rootFolderURL = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
nestedFolderURL = rootFolderURL
if !FileManager.default.fileExists(atPath: nestedFolderURL!.relativePath)
try FileManager.default.createDirectory(
at: nestedFolderURL!,
withIntermediateDirectories: false,
attributes: nil
)
return nestedFolderURL!
catch (let error)
print(error)
return nestedFolderURL!
【讨论】:
以上是关于与 UIActivityViewController 共享 PDF - 文件名的主要内容,如果未能解决你的问题,请参考以下文章
iOS 8.3:UIActivityViewController 显示无关的行
SwiftUI完美弹出UIActivityViewController(通过微信QQ或隔空投送分享)的应用分享窗口
SwiftUI完美弹出UIActivityViewController(通过微信QQ或隔空投送分享)的应用分享窗口