This question already has an answer here:
I was wondering if I could wait for request to be processed with afnetworking.
Lets say I got this method
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
//Request goes here, so the method doesn't return anything before it's processed
}
Is that doable?
You can, but you never want the main queue waiting for some asynchronous operation to complete. If you want something to happen after your asynchronous operation is done, you should use the AFNetworking
success
block to specify what you want to happen when the operation is done.So, if you want to provide the caller a pointer to the
MWPhoto
, rather than having a return type ofMWPhoto *
, have a return type ofvoid
, but supply a completion block so that the caller can handle it when it's done:So, rather than:
You might instead do:
This is exactly what I did, which reffers to starting synchronyous request
This would be referred to a synchronous request.
If the method is called on the main thread it will make your app appear to have frozen and is not a suggested way to do networking.
See the dupe question I commented for details on how to do it if you still want to.
Since AFURLConnectionOperation inherits from NSOperation, you can use NSOperation waitUntilFinished method to wait for the operation to end.
However, the success and failure blocks of AFURLConnectionOperation will be executed before waitUntilFinished completes. Nevertheless, you can access the response and error properties of the AFURLConnectionOperation after waitUntilFinished completes.