【问题标题】:Error copying files with FileManager (CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme)使用 FileManager 复制文件时出错(CFURLCopyResourcePropertyForKey 失败,因为它传递了一个没有方案的 URL)
【发布时间】:2017-12-20 23:54:57
【问题描述】:

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

CFURLCopyResourcePropertyForKey 失败,因为它传递了一个没有方案的 URL 错误 Domain=NSCocoaErrorDomain Code=262 “无法打开文件,因为不支持指定的 URL 类型。”

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

【问题讨论】:

    标签: swift macos-sierra nsfilemanager xcode9-beta


    【解决方案1】:

    发生错误是因为

    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))
    

    【讨论】:

      猜你喜欢
      • 2012-07-31
      • 2014-11-22
      • 2017-08-03
      • 2012-11-30
      • 2014-09-10
      • 1970-01-01
      • 2021-04-01
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多