Error copying files with FileManager (CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme)

假如想象 提交于 2019-12-23 07:21:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!