Easy HTTP downloading

kainjow

Registered
What's the easiest way to download a file in Cocoa? I have some socket classes that use the HTTP protocol, and I have a sample app that uses cURL (complicated), but is there an easier way? I need it only for Cocoa. Thanks!
 
From www.cocoadev.com/index.pl?DownloadingFiles:

Code:
NSURL *myURL = [NSURL URLWithString:@"http://www.apple.com/"];
NSData *urlContents = [myURL resourceDataUsingCache:YES];

if ([urlContents writeToFile:[@"~/Documents/applewebsite.html" stringByExpandingTildeInPath] atomically:YES]) { // It was successful, do stuff here } else { // There was a problem writing the file }


Check the link, it contains sample code for asynchronous downloading as well.
 
Wow thanks a lot. I didn't know it was that easy. I thought the NSUrl thing was for local urls (~/Desktop, etc). This is awesome. (I'm new to Cocoa).
 
Instead if writing to a file, would it be possible to write directly into a textfield?
If so, what line of code should be used?

Txs,
Flor.
 
Code:
NSURL *url = [NSURL urlWithString:@"http://www.apple.com"];
NSString *html = [[NSString alloc] initWithContentsOfURL:url];
[textField setStringValue:html];
 
Also, if you need to get the headers of an HTML document, you can use NSTask and run the cURL unix app with the "--head" attribute thingy and it will return the header. It will look like this in the Terminal:
Code:
curl --head 'http://www.macosx.com'

P.S. If you don't know how to use NSTask to do this, you can use this tutorial: http://www.cocoadevcentral.com/tuto...ow=00000017.php
 
Back
Top