UIDocumentInteractionController изменить имя файла для общего доступа - PullRequest
0 голосов
/ 20 февраля 2020

Я использую следующий код, чтобы показать параметры общего доступа для PDF

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

. Проблема в том, что я сохраняю имя файла PDF с меткой даты, чтобы избежать двух файлов с одинаковым именем, но когда параметры общего доступа показываются, появляется реальное имя файла,

- есть способ показать пользовательское имя вместо фактического имени файла (я не хочу копировать файл в другое место и переименовывать его, тратить впустую времени и производительности) enter image description here

1 Ответ

0 голосов
/ 07 апреля 2020

В такой ситуации мы можем создать временную папку, которая может содержать тот же файл, для которого 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 получает dismiss, удаляет временный filePath по методу 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)")
                }
            }
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...