我从 DocumentPicker(iCloud、保管箱等)下载文件。此文件可以是 .pages、.docx、.pdf...
当我想将其转换为NSData用于文件上传时,我总是收到一个nil值:
if NSFileManager.defaultManager().fileExistsAtPath(urlToFile!.path!) {
let data = NSData(contentsOfURL: urlToFile!) // initializer returns nil, although file and path exist
println(data) // prints nil
}
else {
println("Does not exist")
}
我不明白为什么它是零,文件存在于这个路径! 我的错误在哪里?
更多信息
截图显示这不是范围问题,但初始化程序(如我的问题标题中所述)已经返回 nil。在此示例中,我使用了以下答案中的建议,利用 contentsOfFile
使用错误指针
"The operation couldn’t be completed. (Cocoa error 257.)" UserInfo=0x7fac556cbf00 {NSFilePath=SUPERLONGPATH<NSUnderlyingError=0x7fac570beb20 "The operation couldn’t be completed. Permission denied"})
文件来源
文件通过 DocumentPicker 下载:
let docPicker = UIDocumentPickerViewController(documentTypes: ["public.content"], inMode: UIDocumentPickerMode.Import)
docPicker.delegate = self
docPicker.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
self.presentViewController(docPicker, animated: true, completion: nil)
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
labelDatei.text = "Bereit"
labelDateiChose.text = url.lastPathComponent
urlToFile = url
}
解决方案
碰巧 .pages 和 .numbers "file"不是文件,而是文件夹(容器)。所以不能上传。现在可以使用 .pdf 了。感谢大家的帮助
最佳答案
看起来范围问题。您在大括号内定义局部变量 data
并且它不会在大括号之后存在。
去掉 let
这个词。
这样你就可以从封闭的范围内分配一个变量数据
关于swift - 为什么 NSData(contentsOfURL : url) always nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30627566/