UIDocumentInteractionController文件附件错误

时间:2017-04-02 23:12:08

标签: swift swift3 uidocumentinteraction

所以我正在努力从Xcode导出.txt文件,但每当我尝试导出它时,比如通过电子邮件,它会创建一个没有附件和空消息的电子邮件。当我尝试将其导出到iCloud Drive时,会出现一个白色屏幕,然后离开。当我检查iCloud Drive时,文件不存在。这有什么不对?

let message = testLabel.text

func getDocumentsDirectory() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory as NSString
}

let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")

do{
    try message?.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
}catch let error as NSError{
    testLabel.text = String(describing: error)
}

let documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = NSURL.fileURL(withPath: filePath)
documentInteractionController.uti = "public.data, public.content"
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)

2 个答案:

答案 0 :(得分:4)

问题是您将文档交互控制器声明为调用它的方法中的常量,如:

func someButton() {
    let controller = UIDocumentInteractionController...
}

它不会像那样工作。交互控制器需要是呈现它的类的实例变量,并且每次使用新URL呈现它时都应该重新初始化,如下所示:

var controller: UIDocumentInteractionController!

func someButton() {
    controller = UIDocumentInteractionController(url: someURL)
    controller.presentOptionsMenu...
}

为什么呢?我不知道,但如果您认为这是荒谬的,请提交错误报告。

答案 1 :(得分:0)

您的UTI错了。对于文本文件,您应该使用“public.text”。但是已经存在一个常数 - kUTTypePlainText。您只需要导入MobileCoreServices即可使用它。

import MobileCoreServices

然后:

documentInteractionController.uti = kUTTypePlainText as String

创建控制器时,您还应该使用正确的初始化程序:

let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
documentInteractionController.uti = kUTTypePlainText as String
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)

我只会创建并显示控制器,如果文本不是nil并且您成功写入文件:

if let message = testLabel.text {
    let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")

    do {
        try message.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
        let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
        documentInteractionController.uti = kUTTypePlainText as String
        documentInteractionController.name = "matrixFile"
        documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
    } catch let error as NSError {
        testLabel.text = String(describing: error)
    }
}