本文介绍了使用FileManager复制文件时出错(CFURLCopyResourcePropertyForKey失败,因为它传递了没有方案的URL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FileManagercopyItem(at:path:)将某些文件(媒体)从一个文件夹复制到另一个文件夹,但出现错误:

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:

我正在使用Xcode 9 beta和Swift 4.

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)

推荐答案

发生错误是因为

URL(string: "/Users/xxx/Desktop/Media/")!

创建不带方案的URL.您可以使用

creates a URL without a scheme. You can use

URL(string: "file:///Users/xxx/Desktop/Media/")!

或更简单地

URL(fileURLWithPath: "/Users/xxx/Desktop/Media/")

还请注意,在fileManager.copyItem()中,目的地必须包括文件名,而不仅仅是目的地目录:

Note also that in fileManager.copyItem() the destination mustinclude the file name, and not only the destinationdirectory:

try fileManager.copyItem(at: fileURL,
                    to: location.appendingPathComponent(fileURL.lastPathComponent))

这篇关于使用FileManager复制文件时出错(CFURLCopyResourcePropertyForKey失败,因为它传递了没有方案的URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 21:56