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)