加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 使用FileManager复制文件时出错(CFURLCopyResourceProp

发布时间:2020-12-14 04:43:11 所属栏目:百科 来源:网络整理
导读:我正在尝试使用FileManager的copyItem(at:path :)将一些(媒体)文件从一个文件夹复制到另一个文件夹,但我收到错误: CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme Error Domain=NSCocoaErrorDomain Code=262
我正在尝试使用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.”

我正在使用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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读