user1178380
user1178380

Reputation: 11

Objective-C wait for asynchronous HTTP-Request to finish

I use the following code to execute a HTTP-Request:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

After that I want to use the received data. My problem is that i can't do this in connectionDidFinishLoading, but have to do this on another position in my code. As this is an asynchronous task, how can I verify that I don't start to use the received data before the task is completely done?

Thanks in advance,

Edit: My main problem is that the delegates are called after the code which uses the received data.

Upvotes: 1

Views: 1923

Answers (2)

teriiehina
teriiehina

Reputation: 4761

you just have to keep the received data in an ivar an use it whenever you want. if you really want to be sure, you can also use a BOOL set to YES in

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

don't forget that since iOS 5, the NSURLConnectionDelegate (and DownloadDelegate) have changed.

Upvotes: 2

Wolfgang Schreurs
Wolfgang Schreurs

Reputation: 11834

Download the AFNetworking library and use it for your connections. It has blocks methods, which (to me) are much 'cleaner' to use instead of delegate methods. AFNetworking is available on iOS 4 and higher.

https://github.com/AFNetworking/AFNetworking

Read this post on some basics of AFNetworking:

http://engineering.gowalla.com/2011/10/24/afnetworking/

Upvotes: 0

Related Questions