我正在尝试使用FileManager的copyItem(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.”
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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。