我正在尝试将默认文档目录中某个随机目录中的文件向上移动一个级别。但是在复制时,Swift 给了我错误 Cocoa Error 262: NSFileReadUnsupportedSchemeError
。为什么会出现此错误?我进行了快速搜索,几乎所有遇到此问题的人都试图从相机胶卷中复制文件,但我没有。有什么想法吗?提前致谢。
代码在这里:
private func copyFilesInDirectory(fromDir: String, toDirectory toDir: String, withCompletionHandler handler: ()->()){
println("from: \(fromDir)\nto: \(toDir)")
var error: NSError?
var contents = fileManager.contentsOfDirectoryAtPath(fromDir, error: &error)
if let dirContents = contents{
let enumerator = (dirContents as NSArray).objectEnumerator()
while let file = enumerator.nextObject() as? String{
let filePath = fromDir.stringByAppendingString("/\(file)")
println("copying \(filePath)")
if(fileManager.copyItemAtURL(NSURL(fileURLWithPath: filePath)!, toURL: NSURL(string: toDir)!, error: &error)){
println("COPIED")
}
else{
println("COPY ERROR: \(error!.localizedDescription)")
}
}
handler()
}
}
如果有人感兴趣的话,这是日志:
from: /Users/dolce/Library/Developer/CoreSimulator/Devices/05566649-BABB-44BE-BE6F-AFF7B41E3065/data/Containers/Data/Application/F5A83C94-C177-4826-BDD5-3A50E7508239/Documents/Hello/tmp
to: /Users/dolce/Library/Developer/CoreSimulator/Devices/05566649-BABB-44BE-BE6F-AFF7B41E3065/data/Containers/Data/Application/F5A83C94-C177-4826-BDD5-3A50E7508239/Documents/Hello
copying /Users/dolce/Library/Developer/CoreSimulator/Devices/05566649-BABB-44BE-BE6F-AFF7B41E3065/data/Containers/Data/Application/F5A83C94-C177-4826-BDD5-3A50E7508239/Documents/Hello/tmp/test.png
COPY ERROR: The operation couldn’t be completed. (Cocoa error 262.)
最佳答案
copyItemAtURL()
的toURL
参数不能是目标
目录,但目标文件 的 URL。这可以是
创建于
let destPath = toDir.stringByAppendingPathComponent(file)
你也应该更换
let filePath = fromDir.stringByAppendingString("/\(file)")
与
let filePath = fromDir.stringByAppendingPathComponent(file)
还有一个 copyItemAtPath()
方法可以让你免于
将路径转换为 URL。
关于ios - Swift:复制文件会出现 Cocoa 错误 262,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582292/