Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an http get in cocoa on the iPhone

Tags:

http

cocoa

get

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

like image 546
Atma Avatar asked Apr 01 '09 16:04

Atma


2 Answers

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.

like image 198
Jordan Avatar answered Sep 19 '22 05:09

Jordan


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.

like image 44
Alex Avatar answered Sep 22 '22 05:09

Alex