Atma
Atma

Reputation: 29767

How to do an http get in cocoa on the iPhone

can anyone paste some code on how to do a simple http get in cocoa?

Upvotes: 6

Views: 7776

Answers (2)

Jordan
Jordan

Reputation: 21760

Here you go!

This one grabs an image from a webserver.

    NSURL *url = [ NSURL URLWithString: [ NSString stringWithFormat:@"http://www.somewebsite.com/demo.png"] ]; 
    image = [ [ UIImage alloc ] initWithData: [ NSData dataWithContentsOfURL: url ] ];

or, this one grabs a web page...

    NSURL *url = [ NSURL URLWithString:[ NSString stringWithFormat: @"http://www.google.com/search?q=%@", query ] ];
    NSURLRequest *request = [ NSURLRequest requestWithURL: url ];

To do it asynchronously, you should check out NSURLConnection.

Upvotes: 9

Alex
Alex

Reputation: 26859

Take a look at NSURLConnection. You use it to request a URL, synchronously or (preferably) asynchronously. The full documentation for the URL system is here:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html

But what you really probably want is:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

Apple provides some sample code that should get you started.

Upvotes: 2

Related Questions