2017-07-16 12 views
1

我試圖使用FileManagercopyItem(at:path:)將一些(媒體)文件從一個文件夾複製到另一個文件夾,但我得到錯誤:使用FileManager複製文件時出錯(CFURLCopyResourcePropertyForKey失敗,因爲它傳遞了一個沒有方案的URL)

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和斯威夫特發生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

此錯誤的原因

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

謝謝!現在就開始工作了 – badabing

相關問題