copy a file in swift

To copy a file in Swift, we can use the copyItem method of FileManager. Here is an example:

main.swift
let fileManager = FileManager.default

do {
    let fromUrl = URL(fileURLWithPath: "/path/to/source/file")
    let toUrl = URL(fileURLWithPath: "/path/to/target/file")
    try fileManager.copyItem(at: fromUrl, to: toUrl)
} catch {
    print("Error copying file: \(error)")
}
275 chars
10 lines

In the above code, we first create an instance of FileManager. We then define the source and target URLs of the file that we want to copy. Finally, we call the copyItem method of FileManager, passing in the source and target URLs as its parameters.

The copyItem method will throw an error if it encounters any problems during the copying process. We catch any such errors and print the error message.

gistlibby LogSnag