0

我使用以下代码显示共享选项PDF

    self.documentController = UIDocumentInteractionController(url: url)
    self.documentController.name = "Test name" // not working
    self.documentController.presentOptionsMenu(from: self.shareButton, animated: true)

问题是我用日期戳保存 PDF 文件名以避免两个文件同名,但是当显示共享选项时,实际文件名出现,

有没有办法显示自定义名称而不是实际文件名(我不想将文件复制到其他地方并重命名,浪费时间和性能)在此处输入图像描述

4

1 回答 1

0

在这种情况下,我们可以创建一个临时文件夹,该文件夹可以包含与 lastPathExtension 相同的文件,即 document.fileExtension,我们可以将这个新文件路径传递给UIDocumentInteractionController.init(url: newFileUrl)

例如:

func openUnsupportedFileWithPath(documentName : String, fileurl : URL, fileExtension : String, aDocument: SILDocumentDB? = nil, sourceView: UIView? = nil) -> Void {

    // Create new temporary path
    let paths: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    var newFileUrl: String = paths.appending("/Downloads/TemporaryFolder)")
    newFileUrl = newFileUrl.appendingFormat("%@","\(documentName)")

    let destinationPathUrl : URL
    do {
        // Move newly filePath with new fileName and fileExtension
        destinationPathUrl = URL(fileURLWithPath: destinanewFileUrltionPath)
        try FileManager.default.moveItem(at: fileurl, to: destinationPathUrl)
    } catch {
        print(error)
    }

    //Pass newly filePath to UIDocumentInteractionController
    documentInteractionController = UIDocumentInteractionController.init(url: newFileUrl)
    documentInteractionController?.name = documentName
    documentInteractionController?.delegate = self

    let canPreview = documentInteractionController?.presentPreview(animated: true)
    if (canPreview == false) {
        let activityViewController = UIActivityViewController.init(activityItems: [fileurl], applicationActivities: nil)

        activityViewController.setValue(documentName, forKey: "subject")
        if ISIPAD {
            activityViewController.popoverPresentationController?.sourceView = sourceView ?? self.view
        }
        self.present(activityViewController, animated: true, completion: nil)
    } 
}

并且 UIDocumentInteractionController 被解雇,删除documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController)方法上的临时文件路径。

public func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
        documentInteractionController = nil
        let paths: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath: String = paths.appending("/Downloads/TemporaryFolder)")

        let _fileManager : FileManager  = FileManager.default
        if filePath.length > 0 {
            if _fileManager.fileExists(atPath: filePath) {
                do{
                    try _fileManager.removeItem(atPath: filePath)
                }catch  let error as NSError{

                    print("\(error.localizedDescription)")
                }
            }
        }
    }
于 2020-04-07T04:12:50.357 回答