Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error copying files with FileManager (CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme)

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:

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."

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)
like image 745
ruhm Avatar asked Jul 16 '17 10:07

ruhm


1 Answers

The error occurs because

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

creates a URL without a scheme. You can use

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

or, more simply,

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

Note also that in fileManager.copyItem() the destination must include the file name, and not only the destination directory:

try fileManager.copyItem(at: fileURL,
                    to: location.appendingPathComponent(fileURL.lastPathComponent))
like image 70
Martin R Avatar answered Nov 10 '22 17:11

Martin R