Native framework for copying file on macOS

Is there a framework in macOS that I can use to programmatically copy files and get a progress bar the same as copying files from Finder?

Alternatively, I can do the copy using

cp
or filesystem APIs and use
NSProgressIndicator
to implement the progress bar.


Link to stackoverflow question with screenshot:

https://stackoverflow.com/questions/54716540/native-framework-for-copying-file-on-macos

Replies

Check the following man page. It has everything you need:

https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html

While there’s nowt wrong with

copyfile
, if you’re working with our high-level APIs you’ll probably find
NSFileManager
more approachable. Start here.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I tried NSFileManager and it does copy the file and allows me to react through delegate when error happens.


But another part of my question is how to get the progress bar similar to copying a large file from Finder. I didn't find a way to do it through NSFileManager.

Implementing progress on a file system copy operation is tricky because you have to walk the directory hierarchy twice, once to build a progress target and then again to actually do the copy.

NSFileManager
doesn’t do that, because doing so would slow things down in the case where progress isn’t required. However, you could imagine a world where it would be possible to opt in to this, one where
NSFileManager
was nicely integrated with
NSProgress
. If you’d like to see such support added in the future, I encourage you to file an enhancement request describing your requirements. Please post your bug number, just for the record.

In the meantime, if you need this feature you’ll have to implement it yourself. This is quite tricky in the general case — for example, the cost of copying a large file varies radically depending on whether the volume in question supports cloning — so it’d help if you could make some simplifying assumptions.

Are you copying large directory hierarchies? Or just specific files?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"