开发者

Download an save an image file on HDD with Cocoa

开发者 https://www.devze.com 2023-01-01 11:45 出处:网络
I\'m building a program, and I\'m quite confident using Objective-C, but I don\'t know how to programmatically download a file from the web and copy it on the hard drive.

I'm building a program, and I'm quite confident using Objective-C, but I don't know how to programmatically download a file from the web and copy it on the hard drive. I started with :

NSSt开发者_StackOverflowring url = @"http://spiritofpolo.com/images/logo.png";
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

But then I don't know what to do with the data... that sucks, no ;) Can somebody help?


You're close; the last thing you need is a call to -[NSData writeToFile:atomically:].


While that approach, with the final step provided by fbrereto, will work, it does not handle failure gracefully (indeed, it does not handle any sort of failure at all) and will block your application for the duration of the download.

Use NSURLDownload instead. It requires more code, but broken network connections, cut-off downloads, and inaccessible destination paths will not (necessarily) silently break your app.

0

精彩评论

暂无评论...
验证码 换一张
取 消