Completion handler not being called when containing function is within a while loop - objective-c

I have the following code:
while ( /* Some condition that will not be met in this example */ ) {
if( shouldSendRequest ) {
[launchpad getRequestToken];
}
else {
// Next step
}
}
- (void)getRequestToken {
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[self requestForRequestTokenDidComplete:data withResponse:response withError:error];
}];
}
-(void)requestForRequestTokenDidComplete:(NSData *)data
withResponse:(NSURLResponse *)response withError:(NSError *)error {
// Deal with the returned token
}
The problem I have is that the completion handler in getRequestToken is never being called as long as getRequestToken is inside the while loop. As soon as I comment out the while loop, everything works.
What's happening here and is it possible to prevent it? I has planned to use the while loop to prevent the flow of execution moving on before this (and other) completion handlers had finished doing their thing.

The reason it's not working is because NSURLConnection works along with the runloop to perform the async request. Therefore if you stop the runloop by halting flow within the while statement you are preventing the request from completing.
You will need to artificially pump the runloop or use a background thread.
See:
Asynchronous request to the server from background thread
NSURLConnection sendAsynchronousRequest:queue:completionHandler: making multiple requests in a row?
GCD and async NSURLConnection
And lots of others...

Related

Using semaphore to block many, then release all

I have multiple asynchronous tasks that all depend on an initial async authentication step to succeed. I'm using a semaphore to block all the secure tasks until the authentication completes. It's mostly for timing purposes, as the tasks rely on a secure token obtained at the end of authentication. The authentication involves a network request, and may take several seconds.
The difficulty in my code below seems to be that the dispatch_semaphore_signal() issued after authentication only signals that the first semaphore lock may continue. The second would continue to block. There could in future be many moew blocking tasks, all waiting on the semaphore.
I'm wondering if there is a cleaner way to go about this blocking. I believe that each waiting task could immediately issue another dispatch_semaphore_signal(), thus releasing the next task, and so on. Is there a way to release all blocking semaphores in one call?
Is there a cleaner way to do this with GCD? I'm not adept with GCD, so code snippets help, in the context of the below usage.
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
// in actuality, these 3 may be any where in the app, in different classes, methods, etc
// so a completionHandler is not possible
[self authentication]; // async, could take many seconds
[self authenticatedTask1]; // async
[self authenticatedTask2]; // async
- (void) authentication {
// async url request, assume it is configured here
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
// authenticate
authenticated = TRUE;
secure_token = #"4rjiofwefsdf"; // obtained during auth
dispatch_semaphore_signal(sem);
}];
}
- (void) authenticatedTask1 {
// put on new thread, so semaphore doesn't block program
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
if(!authenticated){
// wait until authenticated
dispatch_semaphore_wait(sem)
}
// continue after authenticated, using secure_token
});
}
- (void) authenticatedTask2 {
// put on new thread, so semaphore doesn't block program
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
if(!authenticated){
// wait until authenticated
dispatch_semaphore_wait(sem)
}
// continue after authenticated, using secure_token
});
}
You can put the authenticated tasks into their own suspended dispatch queue, and resume the dispatch queue once the authentication succeeded.
It is not very elegant but you can call 'dispatch_semaphore_signal' right after 'dispatch_semaphore_wait'. It should solve the problem.
- (void)authenticatedTask1 {
// put on new thread, so semaphore doesn't block program
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
if(!authenticated){
// wait until authenticated
dispatch_semaphore_wait(sem);
dispatch_semaphore_signal(sem); // !!!
}
// continue after authenticated, using secure_token
});
}
You could pass in the methods to be executed in a block to be run in the completltion block, then you wouldn't need to use semaphores. Also you would then not need to bother with the dispatch_async waiting for the semaphore to finish:
[self authenticationWithCompletionBlock:^{
[self authenticatedTask1];
[self authenticatedTask2];
}];
- (void) authenticationWithCompletionBlock:(dispatch_block_t)block {
// async url request, assume it is configured here
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
// authenticate
authenticated = TRUE;
secure_token = #"4rjiofwefsdf"; // obtained during auth
block();
}];
}
If the methods are in the same class, you could just call the methods directly instead of the block.
And if you need to know when both async tasks (in your case authenticatedTask1 and authenticatedTask2) are finished, then you'd need to use dispatch groups.

How do you verify that NSURLConnection was successful

[NSURLConnection sendAsynchronousRequest:mutURLRequest queue:opQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode ==200)
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"MUITCheckinPostSucceeded" object:self userInfo:postDictionary];
}
}];
This is my NSURLConnection and I'm not sure how to check if it was successful. I tried a simple flag but that did not work because the boolean didn't retain the "YES" value outside of the NSURLConnection. This is a school assignment so don't post the correct code I'd just like to know the method I need to implement or how I can tackle this problem in a way I haven't tried yet. Thanks in advance.
Try something like this:
[NSURLConnection sendAsynchronousRequest: myURLRequest
queue: [NSOperationQueue mainQueue]
completionHandler: ^(NSURLResponse *urlResponse, NSData *responseData, NSError *requestError) {
// Check for Errors
if (requestError || !responseData) {
// jump back to the main thread to update the UI
dispatch_async(dispatch_get_main_queue(), ^{
[myLabel setText: #"Something went wrong..."];
});
} else {
// jump back to the main thread to update the UI
dispatch_async(dispatch_get_main_queue(), ^{
[myLabel setText: #"All going well..."];
});
}
}
];
You can update your class properties from the completion block. In this case, if flag was atomic, you can just update it. But if you're setting anything else (e.g. any object properties updated from the resulting data object), you might want to dispatch that back to the main queue to avoid synchronization issues:
self.flag = NO;
[NSURLConnection sendAsynchronousRequest:mutURLRequest queue:opQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSInteger statusCode = -1;
// to be safe, you should make sure `response` is `NSHTTPURLResponse`
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
statusCode = httpResponse.statusCode;
}
if (error)
{
// for diagnostic purposes only
NSLog(#"%s: sendAsynchronousRequest error: %#", __FUNCTION__, error);
}
if (error == nil && statusCode == 200)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.flag = YES;
// set any other class properties here
[[NSNotificationCenter defaultCenter] postNotificationName:#"MUITCheckinPostSucceeded" object:self userInfo:postDictionary];
}];
}
}];
I notice that you're posting a notification. If you have multiple view controllers or model objects listening for that notification, that's fine and a notification makes sense. But if this code was in the view controller and that controller is the only thing that cares about the results, you generally forego the notification and just initiate the update the UI right from the code that's dispatched back to the main queue in that completion block.
One final caveat. Any references to self (or ivars, which have an implicit reference to self) will maintain a strong reference to the object for the duration of the operation (i.e. it will retain it). For example, if you dismiss the view controller while the network operation is in progress, the view controller won't be released until after the network operation is done. That's often fine (as it's just for the duration of the connection ... it's not the dreaded strong reference cycle), especially for a school assignment. But if that's an issue, there are techniques to only use a weak reference to the view controller inside the completion block, thus preventing the retaining of the view controller for the duration of the network operation. But that's beyond the scope of your original question (esp since it leads to a bunch of other questions about whether you want to cancel the network operation or not, when you dismiss the view controller), so I'll leave it at here.

NSURLConnection sendAsynchronousRequest:queue:completionHandler not working in iOS 4.3

I am using [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) in my app. By using this my app is terminated in iOS 4.3 but it is working fine in iOS 5.0.
How to use this in iOS 4.3 can any one help me.
Here's a full implementation that works for me. Feel free to rename it and add as a category on NSURLConnection, or just add it as a local method in the class you're working in.
-(void)sendAsynchronousRequest:(NSURLRequest*)request queue:(NSOperationQueue*)queue completionHandler:(void(^)(NSURLResponse *response, NSData *data, NSError *error))handler
{
__block NSURLResponse *response = nil;
__block NSError *error = nil;
__block NSData *data = nil;
// Wrap up synchronous request within a block operation
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
}];
// Set completion block
// EDIT: Set completion block, perform on main thread for safety
blockOperation.completionBlock = ^{
// Perform completion on main queue
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
handler(response, data, error);
}];
};
// (or execute completion block on background thread)
// blockOperation.completionBlock = ^{ handler(response, data, error); };
// Execute operation
[queue addOperation:blockOperation];
}
EDIT
I had to modify the method because I was making UIKit calls in my completion block (e.g. updating labels etc). So it's actually a bit safer to call completion block on the main thread. (original version commented out)
The method you are trying to use is only available on iOS 5. For earlier OSes, consider using
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
and wrapping it into a new thread to achieve async behavior.
Both H2CO3 and Ken Thomases suggestions are right.
In addition, you could take a look at ios4-implementation-of-nsurlconnection-sendasynchronousrequestqueuecompletio.
If you use the main queue as the queue where the completion handler performs, you could use (as Tom suggested) the delegate pattern. To avoid duplicate code, you could use a wrapper on NSURLConnection delegates mechanism.
In the other case, if you want to maintain the async behaviour and you don't want to deal with sync call (as H2CO3 suggested, note that his suggestion is also valid) and the completion handler performs in a different queue, then I suggest you to wrap the async delegate pattern in a NSOperation class. This approach is quite difficult but you can find a good way of do this in Concurrent Operations Demystified (see both the posts).
Hope it helps.

NSNotificationCenter - Way to wait for a notification to be posted without blocking main thread?

I'm using an AFNetworking client object which makes an asynchronous request for an XML document and parses it.
Also using NSNotificationCenter to post a notification when the document has finished parsing.
Is there a way to wait for a notification to be posted without blocking the main thread?
E.g code:
-(void)saveConfiguration:(id)sender {
TLHTTPClient *RESTClient = [TLHTTPClient sharedClient];
// Performs the asynchronous fetching....this works.
[RESTClient fetchActiveUser:[usernameTextField stringValue] withPassword:[passwordTextField stringValue]];
/*
* What do I need here ? while (xxx) ?
*/
NSLog(#"Fetch Complete.");
}
Basically I'm wondering what sort of code I need in the above specified area to ensure that the function waits until the fetch has been completed ?
As it is right now I'll see "Fetch Complete." in the debug console before the fetch has been completed.
I tried adding a BOOL flag to the TLHTTPClient class:
BOOL fetchingFlag;
and then trying:
while([RESTClient fetchingFlag]) { NSLog(#"fetching...); }
When this class receives the notification it sets RESTClient.fetchingFlag = FALSE; which should technically kill the while loop right? Except my while loop runs infinitely ?!
Basically I'm wondering what sort of code I need in the above specified area to ensure that the function waits until the fetch has been completed ?
You need no code. Don't put anything in the method after you start the fetch, and nothing will happen. Your program will "wait" (it will actually be processing other input) until the notification is recieved.
In the notification handler method, put all the stuff that you need to do when the fetch is completed. This is (one of) the point(s) of notifications and other callback schemes -- your object won't do anything further until it gets the notification that it's time to act.
Is there a way to wait for a notification to be posted without blocking the main thread?
That's exactly how it works already.
If you don't need to inform multiple objects upon completion of the task, you could add a completion handler (objc block) to the -fetchActiveUser:withPassword: method (so it would become something like -fetchActiveUser:withPassword:completionHandler: and add the code to be executed in the completion handler.
An example, lets say your -fetchActiveUser:withPassword:completionHandler: method looks like the following:
- (void)fetchActiveUser:(NSString *)user
withPassword:(NSString *)pass
completionHandler:(void (^)(TLUser *user, NSError *error))handler
{
NSURL *URL = [NSURL URLWithString:#"http://www.website.com/page.html"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSOperationQueue *queue = [NSOperationQueue currentQueue];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^ (NSURLResponse *response, NSData *data, NSError *error)
{
if (!handler)
{
return
};
if (data)
{
TLUser *user = [TLUser userWithData:data];
if (user)
{
handler(user, nil);
}
else
{
NSError *error = // 'failed to create user' error ...
handler(nil, error);
}
}
else
{
handler(nil, error);
}
}];
}
The completion handler will be called whenever the task is finished. It will either return a TLUser object or an Error if something went wrong (bad connection, data format changed while parsing, etc...).
You'll be able to call the method like this:
- (void)saveConfiguration:(id)sender
{
TLHTTPClient *RESTClient = [TLHTTPClient sharedClient];
// Performs the asynchronous fetching
[RESTClient fetchActiveUser:[usernameTextField stringValue]
withPassword:[passwordTextField stringValue]
completionHandler:^ (TLUser *user, NSError *error)
{
if (user)
{
NSLog(#"%#", user);
}
else
{
NSLog(#"%#", error);
}
}];
}
Of course, in this example I've used the build in asynchronous methods of NSURLConnection in stead of AFNetworking, but you should be able to get the general idea.

GCD and async NSURLConnection

I know that if I create an NSURLConnection (standard async one), it will call back on the same thread. Currently this is on my main thread. (work fine too).
But i'm now using the same code for something else, and I need to keep my UI snappy....
If i do
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/* and inside here, at some NSURLConnection is created */
});
.. is it possible that my NSURLConnection is created but my thread disappears before the url connection has returned?
I'm new to GCD. How would one keep the thread alive until my url connection returned, or is there a better way I could be doing this?
So really the issue isn't the lifetime of the thread on which your block runs, it's the fact that this particular thread is not going to have a runloop configured and running to receive any of the events coming back from the connection.
So how do you solve this? There are different options to think about. I can list a few, and I'm sure others will list more.
1 - You could use a synchronous connection here. One disadvantage is that you won't get callbacks for authentication, redirection, caching, etc. (All the normal disadvantages of synchronous connections.) Plus each connection will of course block a thread for some period of time, so if you're doing a lot of these then you could potentially have a few threads blocked at once, which is expensive.
2 - If your connection is simple and you are using iOS5 then you can use this method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue*) queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))
This will start an asynchronous connection and then allow you to specify a completion handler (for success or failure) and a NSOperationQueue on which you want that block to be scheduled.
Again, you have the disadvantages of not getting the callbacks you might need for authentication, caching, etc. But at least you don't have threads hanging around blocked by connections that are in flight.
3 - Another option for iOS5 is to set the queue for all delegate callbacks:
- (void)setDelegateQueue:(NSOperationQueue*) queue NS_AVAILABLE(10_7, 5_0);
If you use this, then all of the delegate methods will be executed in the context of whatever NSOperationQueue you specify. So this is similar to option #2, expect that you get all of the delegate methods now to handle authentication, redirection, etc.
4 - You could set up your own thread that you control specifically for managing these connections. And in setting up that thread, you configure a runloop appropriately. This would work fine in iOS4 and 5 and obviously gives you all of the delegate callbacks that you want to handle
5 - You might think about what parts of your asynchronous connection handling are really interfering with your UI. Typically kicking off the connection or receiving delegate callbacks are not that expensive. The expensive (or indeterminate) cost is often in the processing of the data that you collect at the end. The question to ask here is are you really saving time by scheduling a block on some queue just to start an asynchronous connection that will go off immediately and do its thing on another thread anyway?
So you could just start the connection from the main thread, and receive all of the delegate callbacks on the main thread, and then in your implementation of those delegate methods fire off whatever expensive work you need to do on some other queue or thread.
So something like this:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// go ahead and receive this message on the main thread
// but then turn around and fire off a block to do the real expensive work
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Parse the data we've been collecting
});
}
Again, this is not comprehensive. There are many ways to handle this, depending on your specific needs here. But I hope these thoughts help.
Just as an answer to why your thread was disppearing (and for future reference) the NSURLConnection needs a runloop. If you had added
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
You'd see that the connection runs properly and the thread doesn't disappear untill the connection was completed.
First off, your block and every variable you use within it will get copied to GCD, so the code will not be executed on your thread but on the global queue.
If you want to get your data back on the main thread, you can nest an async call after your data has been fetched:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"www.stackoverflow.com"]];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
// handle error
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
// do something with the data
});
});
But why not use NSURLConnection's built in asynchronous support? You need an NSOperationQueue, but if you are doing alot of network fetches it is the way to go anyway:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"www.stackoverflow.com"]];
[NSURLConnection sendAsynchronousRequest:request
queue:self.queue // created at class init
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
// do something with data or handle error
}];
Personally, I use a library like AFNetworking or ASIHTTPRequest to make networking even easier, which both support blocks (the former utilizes GCD and is a bit more modern).
dispatch_queue_t queue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[btnCreateSmartList setEnabled:NO];
[dbSingleton() createEditableCopyOfDatabaseIfNeeded];
[dbSingleton() insert_SMART_PlaceList:txtListName.text :0:txtTravelType.text: [strgDuration intValue]:strgTemprature:Strgender:bimgdt];
[self Save_items];
//*********navigate new
dispatch_async(dispatch_get_main_queue(), ^{
[activityIndicator stopAnimating];
[self performSelector:#selector(gonext_screen) withObject:nil afterDelay:0.0];
});
});