Execute a method after the completion of another method - ios

In my app i have two methods, storeData and gotoNextView. I want the gotoNextPage to be executed after storeData method has completed execution. In storeData i am saving the token obtained after sucessful login using Egocache, in gotoNextPage i have code which is used to load a new view controller, in the next viewcontroller i have to use the token for fetching the other details. But the problem the method gotoNextView is being executed before the storeData so i am gettin null token in the next view.
I have tried using the following :
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
[self storeData];
});
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
[self gotoNextPage];
the above code is serving the purpose but when i am using the above code, the NSUrlConnections in the next view are not loading.
[self storeData];
[self performSelector:#selector(gotoNextPage) withObject:nil afterDelay:1.0f];
this code is working and the NSUrlConnections in next view also working, but is there a better way to achieve this purpose

You could pass a completion block to the storeData method. That way storeData can let you know when it's finished doing what it needs to do, instead of you trying to guess.
- (void)storeDataWithCompletion:(void (^)(void))completion
{
// Store Data Processing...
if (completion) {
completion();
}
}
// Calling storeDataWithCompletion...
[self storeDataWithCompletion:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self gotoNextPage];
});
}];
The dispatch_async to the main queue is not required. I added that since gotoNextPage is UI related and it's not clear what thread storeDataWithCompletion: would call the completion block from.
Here's a link to Apple's documentation on blocks
Hope this helps.

Related

Issues related to calling UIKit methods from non-main thread

I implemented login method in this way:
[KVNProgress show];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//some error handling like:
if ([_usernameField.text length] < 4) {
[KVNProgress showErrorWithStatus:#"Username too short!"];
_passwordField.text = #"";
return;
}
//Then I call login web service synchronously here:
result = [ServerRequests login];
dispatch_async(dispatch_get_main_queue(), ^{
if(!result)
{
[KVNProgress showErrorWithStatus:#"problem!" completion:NULL];
_passwordField.text = #"";
}
else if([result.successful boolValue])
{
[KVNProgress showSuccessWithStatus:result.message];
}
});
});
It crashed mostly and by surrounding blocks with only Main Queue (no priority default one) that solved! but the problem is:KVNProgress is only showing in error handling area not the next part that we call web service. It's not user friendly at all! Any idea is welcomed :)
You MUST call methods that update the user interface in any way from the main thread, as per the UIKit documentation:
For the most part, use UIKit classes only from your app’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your app’s user interface in any way.
I suggest you try to limit the number of callbacks you make to the main thread, so therefore you want to batch as much user interface updates together as you can.
Then all you have to do, as you correctly say, is to use a dispatch_async to callback to your main thread whenever you need to update the UI, from within your background processing.
Because it's asynchronous, it won't interrupt your background processing, and should have a minimal interruption on the main thread itself as updating values on most UIKit components is fairly cheap, they'll just update their value and trigger their setNeedsDisplay so that they'll get re-drawn at the next run loop.
From your code, it looks like your issue is that you're calling this from the background thread:
if ([_usernameField.text length] < 4) {
[KVNProgress showErrorWithStatus:#"Username too short!"];
_passwordField.text = #"";
return;
}
This is 100% UI updating code, and should therefore take place on the main thread.
Although, I have no idea about the thread safety of KVNProgress, I assume it should also be called on the main thread as it's presenting an error to the user.
Your code therefore should look something like this (assuming it's taking place on the main thread to begin with):
[KVNProgress show];
//some error handling like:
if ([_usernameField.text length] < 4) {
[KVNProgress showErrorWithStatus:#"Username too short!"];
_passwordField.text = #"";
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Then I call login web service synchronously here:
result = [ServerRequests login];
dispatch_async(dispatch_get_main_queue(), ^{
if(!result) {
[KVNProgress showErrorWithStatus:#"problem!" completion:NULL];
_passwordField.text = #"";
} else if([result.successful boolValue]) {
[KVNProgress showSuccessWithStatus:result.message];
}
});
});

Issue in execute a method after completion of another method - iOS

I have two methods as loadTopicPostsFromDB and loadTopicPosts. In the loadTopicPostsFromDB method I am updating the value of a global NSString called strLastTimeStamp which should use in the loadTopicPosts. Thus, I want to execute loadTopicPostsFromDB first and after it finished(global string updated) I want to execute loadTopicPosts method.
This is how I did it. But, currently loadTopicPosts method executes before updating the global strLastTimeStamp, so always I get a wrong strLastTimeStamp.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
[self performSelectorOnMainThread:#selector(loadTopicPostsFromDB) withObject:nil waitUntilDone:NO];
});
dispatch_group_notify(group, queue, ^{
NSLog(#"LoadDBCompleted");
[self loadTopicPosts];
});
How can I do this, please advice me on what is the wrong in this implementation.
performSelectorOnMainThread: is finished as soon as iOS has put the task into a queue. The selector has most likely not even started running when the call returns. And really, you shouldn't be using performSelectorOnMainThread at all - the function isn't available in Swift, for good reason. The solution is a lot easier (fix the problems yourself):
dispatch_async (dispatch_get_main_queue (), ^{
[self loadTopicsFromDB];
[self loadTopicPosts];
});
You probably want to perform loadTopicsFromDB on a background thread though.
When you are doing something using network connection I advice you to use blocks to handle the endpoint of the call.
It is pretty simple to write in this code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self loadTopicsFromDB: ^(BOOL success, NSError *error) {
[self loadTopicPosts];
}];
});

How to ensure completion of a async operation before continuing with execution

I am building an iOS app and some part of its code relies on the success/failure value returned from a particular task.This tasks involves callbacks from a library. I want the return value from this task to be returned only after the callback has returned either success/failure. But since I wrote a sequential code the return value is returned even before the callback returns a success/failure.
I looked into using modal view controllers and from what I understand I can make the task execute from this view controller and then return the code back.
But this also doesn't suit my requirements as when the code which initiates the callback sequence is executed I don't want a new view controller to be displayed. Although there is a certain callback which requires me to prompt the user for information. I do this in a popover and I considered making the view controller within the popover modal. But then the callbacks will still be part of the main thread and I won't receive them when my popover is presented modally(?).
With my current understanding of these concepts I don't know how to proceed. Is there some way to do this in iOS?
EDIT:
The code does something like this
//In CustomTableViewController
-(void) someFunc
{
ENUM_NAME code = [TaskController startTheTask:args];
if(code == SUCCEEDED)
{
//Do Something
}
if(code == FAILED)
{
//Do Something Else
}
}
//In TaskController
-(ENUM_NAME) startTheTask:args
{
startWorkflow(args); //This function registers callback function with the library.
return finalCode; //This is returned even before it is set to SUCCEEDED/FAILED
}
-(void) onCallback:params
{
MSG_TYPE msg = [params getMsg];
if(msg == TASK_FAILED)
finalCode = FAILED;
if(msg == TASK_SUCCEEDED)
finalCode = SUCCEEDED;
if(msg == TASK_SHOW_PROMPT)
{
[PopOverController showPopOver];
}
}
-(void) onUserInfoAdded
{
//This is called when Confirm is clicked in the popover
continueWorkflow(params); //asks for the next callback to happen
}
-(void) onCancleClicked
{
//This is called when Popover is dismissed without entering Info
cancleWorkflow(params); //asks for result of the workflow through callback
}
You can use GCD. For example:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
//put one process here
dispatch_group_leave(group); //when done
});
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
//put another process here
dispatch_group_leave(group); //when done
});
// All updates finished
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// add last steps here after all processess are finished
});
dispatch_release(group);
You can use a semaphore to delay the execution until a block returns:
__block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block NSData *dataFromTheBlock = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// block implementation
// dataFromTheBlock = some data;
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

What is the best way to load data inside a Viewcontroller

I'm writing an iOS app that is getting data from a server. I have several ViewControllers. I used to load data for that viewcontroller under the viewDidLoad method
-(void)ViewDidload
{
[self loadData];
}
-(void)loadData
{
//calling to webservice caller class
}
But this reduces the app's performance. What is the best method to load data within a viewcontroller? For webservice callings, I have a seperate class. Within my loadData method I call to that particular method inside the webservice calling class.
This is going to block my UI.
What do you mean with "this reduces the app performance". Your app is lagging when you are calling your webservice? This is not because you are calling that in viewDidLoad this is because you are doing that in the main thread.
To call your webservice you can use:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// Call here your web service
dispatch_sync(dispatch_get_main_queue(), ^{
// push here the results to your ViewController
});
});
With this simple solution you are downloading data from your webservice in a separate thread. And pushing the data to your ViewController with the mainThread. This code is not freezing your app. However you will have a moment that nothing happens. This is a good moment to use a UIActivityIndicatorVew.
I guess your interface is lagging.
Try this:
-(void)ViewDidload
{
[NSThread detachNewThreadSelector:#selector(loadData) toTarget:self withObject:nil];
}

Handle concurrency and asynchronous response

I am trying to implement concurrency in objective C. I have a problem with an actions that needs to be run in a synchronized way. The problem here is that I use function that executes a block after completion.
I want to connect to a bluetooth device to run some operations and connect to the next device.
for (Beacon * beacon in beacons) {
[beacon setDelegate:self];
[beacon connectToBeacon];
}
But the connection is asynchronous. The beacon call the delegate (in this case it's the same class) method didConnectSuccess when connection is successful.
I need to wait all my operations in "beaconDidConnect" and deconnection to finish before connecting to the next device.
I currently use a combination of dispatch queue and dispatch semaphore, my semaphore is an ivar
dispatch_queue_t myCustomQueue;
myCustomQueue = dispatch_queue_create("com.example.MyCustomQueue", NULL);
for (Beacon * beacon in beacons) {
[beacon setDelegate:self];
dispatch_async(myCustomQueue, ^{
dispatch_semaphore_wait(semaphoreBluetooth, DISPATCH_TIME_FOREVER);
[beacon connectToBeacon];
});
}
In combination with
- (void)beaconDidDisconnect:(Beacon *)beacon
{
dispatch_semaphore_signal(semaphoreBluetooth);
}
Without the dispatch_async, by blocking the callback (beaconDidConnect), the wait was causing a deadlock.
I wanted to dispatch_semaphore_wait in the for loop and not in the dispatch block but the wait causes the callback to wait again, causing a deadlock.
This way it seems to work but I found it a bit ugly.
My other issue is that in my beaconDidConnect method I need to chain asynchronous call and in each waiting the previous to terminate.
All those calls have a termination block, executing when the call is done. I could write instructions in deeper and deeper block but I'd like to avoid this.
I'd need an equivalent of the javascript "promise" concept.
Currently I have something with dispatch queue and dispatch semaphore but I sometimes have deadlock for unknown reason.
Eg :
- (void)beaconConnectionDidSucceeded:(Beacon *)beacon
{
dispatch_semaphore_t semaphoreEditing = dispatch_semaphore_create(1);
dispatch_queue_t editingQueue = dispatch_queue_create("com.example.MyCustomQueue.Editing", NULL);
// First writing procedure
dispatch_async(editingQueue, ^{
dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
[beacon writeSomeCaracteristic:caracteristic withValue:value withCompletion:^(void) {
dispatch_semaphore_signal(semaphoreEditing);
}];
});
// A unknow number of writing sequences
dispatch_async(editingQueue, ^{
dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
[beacon writeSomeCaracteristic:caracteristic withValue:value withCompletion:^(void) {
dispatch_semaphore_signal(semaphoreEditing);
}];
});
//
// ...
//
dispatch_async(editingQueue, ^{
dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
[beacon writeSomeCaracteristic:caracteristic withValue:value withCompletion:^(void) {
dispatch_semaphore_signal(semaphoreEditing);
}];
});
// Terminate the edition
dispatch_async(editingQueue, ^{
dispatch_semaphore_wait(semaphoreEditing, DISPATCH_TIME_FOREVER);
[beacon disconnectBeacon];
dispatch_semaphore_signal(semaphoreEditing);
});
}
I want to write clear code that execute my instructions in a sequential way.
If your asynchronous methods do have a completion handler, you can "serialize" or "chain" a number of asynchronous calls like shown below:
[self asyncFooWithCompletion:^(id result){
if (result) {
[self asyncBarWithCompletion:^(id result){
if (result) {
[self asyncFoobarWithCompletion:^(id result){
if (result) {
...
}
}];
}
}];
}
}];
Of course, this gets increasingly confusing with the number of chained asynchronous calls, and especially when you want to handle errors, too.
With a third party library which especially helps to overcome these problems (including error handling, cancellation) it may look similar as the code below:
Given:
- (Promise*) asyncFoo;
- (Promise*) asyncBar;
- (Promise*) asyncFoobar;
"Chaining" the three asynchronous methods including error handling:
[self asyncFoo]
.then(^id(id result){
... // do something with result of asyncFoo
return [self asyncBar];
}, nil)
.then(^id (id result){
... // do something with result of asyncBar
return [self asyncFoobar];
}, nil)
.then(^id(id result) {
... // do something with result of asyncFoobar
return nil;
},
^id(NSError*error){
// "catch" any error from any async method above
NSLog(#"Error: %#", error);
return nil;
});
For general info about "Promises", please read wiki article Futures and Promises.
There are number of Objective-C libraries which implement a Promise.
Have you considered use NSOperation and NSOperationQueue?
If you need to wait for every beacon to run a set of operations before continue, you can store every set of operations in a NSOperation and put all the operations inside a NSOperationQueue with a maxConcurrentLimit of 1. It might be easier to cancel/pause/terminate every single operation and the queue will take care of the concurrency.
I kept the dispatch_queue and dispatch_semaphore for the connection but for the writing actions I use a library called Sequencer I found here.
It follows the Promises principle CouchDeveloper talked about.

Resources