ios - Swift:复制文件会出现 Cocoa 错误 262

标签 ios swift

我正在尝试将默认文档目录中某个随机目录中的文件向上移动一个级别。但是在复制时,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/

相关文章:

ios - 为什么 Apple 建议在串行后台队列中分派(dispatch) OpenGL 命令,因为这不可避免地会导致崩溃?

swift - 如何在 Swift 2 中访问 JSON 数组的元素

ios - 导航 Controller 和状态栏问题

ios - 不显示所有用户的用户数据,如何只显示喜欢该登录用户的人的数据?

iOS:动画颜色从左到右变化

ios - 丢弃从某个点开始的所有核心数据更改

ios - UIView 页面 curl 动画不适用于 block

iphone - 使用 GCD 执行 sudzc Web 服务

ios - 使用自动布局在 UICollectionView 中指定单元格的一维

swift - 如何检查用户是否在特定区域