views:

2055

answers:

3

Our iPhone app code currently uses NSURLConnection sendSynchronousRequest and that works fine except we need more visibility into the connection progress and caching so we're moving to an async NSURLConnection.

What's the simplest way to wait for the async code to complete? Wrap it in a NSOperation/NSOperationQueue, performSelector..., or what?

Thanks.

+2  A: 

To use NSURLConnection asynchronously you supply a delegate when you init it in initWithRequest:delegate:. The delegate should implement the NSURLConnection delegate methods. NSURLConnection processing takes place on another thread but the delegate methods are called on the thread that started the asynchronous load operation for the associated NSURLConnection object.

m4rkk
Hi,Right, got that. But, the bit I'm wrestling with is how to wait/block in the other thread until the request is complete.Thanks.
denton
@denton you don't want to block. When the request completes you notify your main (or other) thread. NSNotificationCenter is one way.
John Fricker
+4  A: 

I'm answering this in case anyone else bumps into the issue in the future. Apple's URLCache sample code is a fine example of how this is done. You can find it at:

https://developer.apple.com/iphone/library/samplecode/URLCache/index.html

As John points out in the comment above - don't block/wait - notify.

denton
+1  A: 

Apart from notifications mentioned prior, a common approach is to have the class that needs to know about the URL load finishing set itself as a delegate of the class that's handling the URL callbacks. Then when the URL load is finished the delegate is called and told the load has completed.

Indeed, if you blocked the thread the connection would never go anywhere since it works on the same thread (yes, even if you are using the asynch methods).

Kendall Helmstetter Gelner