问题
I'm trying to copy some (media) files from one folder to another using FileManager
's copyItem(at:path:)
, but I'm getting the error:
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."
I'm using Xcode 9 beta and 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)
回答1:
The error occurs because
URL(string: "/Users/xxx/Desktop/Media/")!
creates a URL without a scheme. You can use
URL(string: "file:///Users/xxx/Desktop/Media/")!
or, more simply,
URL(fileURLWithPath: "/Users/xxx/Desktop/Media/")
Note also that in fileManager.copyItem()
the destination must
include the file name, and not only the destination
directory:
try fileManager.copyItem(at: fileURL,
to: location.appendingPathComponent(fileURL.lastPathComponent))
来源:https://stackoverflow.com/questions/45127390/error-copying-files-with-filemanager-cfurlcopyresourcepropertyforkey-failed-bec