views:

1049

answers:

6

I am writing a cocoa application in which I want to download a file from a webserver. What will be the most convenient method to go about doing this? Should I go in for NSSockets or a NSUrlRequest? Or is there any other easier way to achieve this?

+1  A: 

The simplest thing to do is probably use NSURLDownload with NSURLRequest.

Ben Gottlieb
+4  A: 

If you want to load the contents of the file into memory, many of the Cocoa data classes such as NSString, NSData and even NSDictionary have initWithURL: methods, which initialize directly with the contents of a web request. They're very easy to use, but they're not very flexible or provide for good error handling. NSURLConnection provides a more flexible way to load data if you need it.

If you want to download the file directly to disk, then NSURLDownload would be the best bet.

Marc Charbonneau
+2  A: 

A word of warning: The initWithURL: methods are blocking, which is a big problem if the file is large, the server is slow, the user's internet connection is slow, etc. Don't call them from the main thread.

You also don't get any progress reporting, so when the download is slow, you have no way to tell the user how far along it is or how much longer it will take.

In almost all cases, you should use NSURLDownload or NSURLConnection instead.

Peter Hosey
A: 

And another way is using libcurl, which comes preinstalled on any OS X system. You'd better make sure System Settings like proxies etc. are respected though if you use this approach.

Kristof
+1  A: 

NSURLConnection is good if you want to get data from the web service into an NSString or NSData. Make sure you make asynchronous calls and handle errors and data in the NSURLConnection methods

Here's a good example for REST-style calls http://kosmaczewski.net/2008/03/26/playing-with-http-libraries/

lostInTransit
+1  A: 

NSURLConnection does give you the most granularity, but be careful with NSURLConnection's sendSynchronousRequest() method. It leaks memory each time (have attached the XCode Leak Instrumentation tool and run it to prove it to myself) and gives weird HTTP 204 responses for no reason at all on occasion. I've blogged about this here

Matthew McCullough