swift - 使用 FileManager 复制文件时出错(CFURLCopyResourcePropertyForKey 失败,因为它传递了一个没有方案的 URL)

标签 swift macos-sierra nsfilemanager xcode9-beta

我正在尝试使用 FileManagercopyItem(at:path:) 将一些(媒体)文件从一个文件夹复制到另一个文件夹,但我得到了错误:

CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported."

我正在使用 Xcode 9 beta 和 Swift 4。

let fileManager = FileManager.default
let allowedMediaFiles = ["mp4", "avi"]

func isMediaFile(_ file: URL) -> Bool {
    return allowedMediaFiles.contains(file.pathExtension)
}

func getMediaFiles(from folder: URL) -> [URL] {
    guard let enumerator = fileManager.enumerator(at: folder, includingPropertiesForKeys: []) else { return [] }

    return enumerator.allObjects
        .flatMap {$0 as? URL}
        .filter { $0.lastPathComponent.first != "." && isMediaFile($0)   
    }
}

func move(files: [URL], to location: URL) {
    do {
        for fileURL in files {
            try fileManager.copyItem(at: fileURL, to: location)
        }
    } catch (let error) {
        print(error)
    }
}


let mediaFilesURL = URL(string: "/Users/xxx/Desktop/Media/")!
let moveToFolder = URL(string: "/Users/xxx/Desktop/NewFolder/")!

let mediaFiles = getMediaFiles(from: mediaFilesURL)

move(files: mediaFiles, to: moveToFolder)

最佳答案

错误发生是因为

URL(string: "/Users/xxx/Desktop/Media/")!

创建一个没有方案的 URL。你可以使用

URL(string: "file:///Users/xxx/Desktop/Media/")!

或者,更简单地说,

URL(fileURLWithPath: "/Users/xxx/Desktop/Media/")

另请注意,在 fileManager.copyItem() 中,目的地必须 包括文件名,而不仅仅是目的地 目录:

try fileManager.copyItem(at: fileURL,
                    to: location.appendingPathComponent(fileURL.lastPathComponent))

关于swift - 使用 FileManager 复制文件时出错(CFURLCopyResourcePropertyForKey 失败,因为它传递了一个没有方案的 URL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45127390/

相关文章:

maven-3 - 为什么我在 ~/.m2 下找不到我的 settings.xml?

php - macOS Sierra 中的更改阻止 "say"在 PHP 脚本中执行

ios - Swift 3 将图像添加到文档并检索

objective-c - 在设备上找不到 NSBundle 文件夹,但在模拟器中工作

ios - 如何在 SWIFT 3 中将 HTTPS 代理添加到 NSURLSession

swift - 如何在 NsmutableArray 中快速获取 google 地点 id?

ios - 如何获取具有最大 ID 的项目?

macos - 为什么 macOS 系统打印比 Chrome 或 lpr 更快?

ios - NSFileManager.defaultManager().fileExistsAtPath 返回 false 而不是 true

objective-c - 按下按钮时如何禁用按钮数组中的其余按钮