[英]UIDocumentInteractionController file attachment error
因此,我正在嘗試從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)
問題是您正在將文檔交互控制器聲明為調用它的方法中的常量,例如:
func someButton() {
let controller = UIDocumentInteractionController...
}
它不會那樣工作。 交互控制器必須是呈現它的類的實例變量,並且每次您使用新的URL呈現它時都應重新初始化它,如下所示:
var controller: UIDocumentInteractionController!
func someButton() {
controller = UIDocumentInteractionController(url: someURL)
controller.presentOptionsMenu...
}
為什么? 我不知道,但是如果您認為這是荒謬的,請提交錯誤報告。
您的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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.