views:

815

answers:

4

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

+2  A: 

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... :)

h4xxr
Just remember that the `NSArray` and `NSDictionary` "ContentsOfURL:" methods require that the target resource be in plist format.
Dave DeLong
+3  A: 

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.

Jasconius
great link :) thank you, useful sometimes :)
balexandre
+5  A: 
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:aURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
Dave DeLong
+1  A: 

you should never considerate this over iPhone/iPad devices or any mobile device at all!

what will happen if the WiFi Connection is, for some reason not good and there is no clear path to the web?

the user sees an App hanging!

and I'm almost sure that Apple will reject it as they clear state that you need to provide an Activity spinner or some kind of interface to let the user know that he/she should wait for an operation.

Taking this aside, there are plenty of ways to handle this, one of the best ways and several tutorials could be found is when using the Cocoa Touch JSON Framework

balexandre
There are plenty of times you can use this. I have an app that downloads some data and then does extensive processing on it. I can spawn a thread, run the synchronous download call, and when that finishes do my processing on that thread. The main thing you loose is the ability to show a download progress, but you can use a spinner.
jamone