Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPad/objective-C synchronous HTTP request example?

I can only find asynchronous iPad/objective C HTTP examples. How do I do a synchronous web request?

like image 697
MikeN Avatar asked Apr 20 '10 14:04

MikeN


3 Answers

NSURLRequest * urlRequest = [NSURLRequest requestWithURL:aURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
like image 98
Dave DeLong Avatar answered Oct 20 '22 18:10

Dave DeLong


Agree with h4xxr and I would forward you to

http://allseeing-i.com/ASIHTTPRequest/

Which is a fantastic lib that has robust HTTP request methods for both synch and asynch complete with code samples.

like image 27
M. Ryan Avatar answered Oct 20 '22 19:10

M. Ryan


Depends on what data you're after. Something simple like this is synchronous, and is handy from time to time:

NSURL *url = [NSURL URLWithString:@"http://someaddress.asp?somedatarequest=1"];
NSArray *dataArray = [NSArray arrayWithContentsOfURL:url];

(Equivalent also exists for Dictionaries)

In this case, the system will wait for a response from someaddress.asp - therefore best perhaps to put something like this into a background thread.

If you have control over the format of the data at the other end, this can be a quick and easy way to get data into an iPhone/iPad app...

Edit - just wanted to state the obvious that typically asynchronous is usually best! No waiting around tying up system resources, especially if remote server has died etc... :)

like image 31
h4xxr Avatar answered Oct 20 '22 20:10

h4xxr