Update UI (activityIndicator) in dispatch_sync queue (Objective C) - ios

This is my Sign In button :
- (IBAction)signInButtonAction:(id)sender
{
if ([self.phoneNumberTextField.text length] == 0 || [self.passwordTextField.text length] == 0) {
[self initializeAlertControllerForOneButtonWithTitle:#"Alert!" withMessage:kEmptyTextFieldAlertMSG withYesButtonTitle:#"Ok" withYesButtonAction:nil];
} else {
if ([self alreadyRegisteredPhoneNumber] == YES) {
if ([self.password isEqualToString:self.passwordTextField.text]) {
[self goToHomeViewController];
} else {
[self initializeAlertControllerForOneButtonWithTitle:#"Wrong Password!" withMessage:kWrongPasswordMSG withYesButtonTitle:#"Ok" withYesButtonAction:nil];
}
} else {
[self initializeAlertControllerForOneButtonWithTitle:#"Alert!" withMessage:kSignInPhoneNumberDoesnotExistMSG withYesButtonTitle:#"Ok" withYesButtonAction:nil];
}
}
}
And this is my alreadyRegisteredPhoneNumber method, where I am just checking if the given phone number is registered or not.
- (BOOL)alreadyRegisteredPhoneNumber
{
[self.activityIndicator startAnimating];
__block BOOL isThisPhoneNumberRegistered = NO;
BlockWeakSelf weakSelf = self;
SignInViewController *strongSelf = weakSelf;
dispatch_sync(dispatch_queue_create("mySyncQueue", NULL), ^{
NSString *PhoneNumberWithIsoCountryCode = [NSString stringWithFormat:#"%#%#", strongSelf.countryCode, strongSelf.phoneNumberTextField.text];
strongSelf.userModelClass = [[RetrieveDataClass class] retrieveUserInfoForPhoneNumber:PhoneNumberWithIsoCountryCode];
if ([strongSelf.userModelClass.phone_number length] != 0) {
strongSelf.phoneNumber = strongSelf.userModelClass.phone_number;
strongSelf.password = strongSelf.userModelClass.password;
isThisPhoneNumberRegistered = YES;
[strongSelf.activityIndicator stopAnimating];
}
});
return isThisPhoneNumberRegistered;
}
With this method the problem is that the activityIndicator is not appearing when I press Sign In button. Otherwise it works synchronize way, which is perfect.
The reason activityIndicator is not appearing is that I have to update UI related change in dispatch_async(dispatch_get_main_queue() (Or not??). But If I rearrange my code like this :
- (BOOL)alreadyRegisteredPhoneNumber
{
[self.activityIndicator startAnimating];
__block BOOL isThisPhoneNumberRegistered = NO;
BlockWeakSelf weakSelf = self;
SignInViewController *strongSelf = weakSelf;
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_sync(dispatch_queue_create("mySyncQueue", NULL), ^{
NSString *PhoneNumberWithIsoCountryCode = [NSString stringWithFormat:#"%#%#", strongSelf.countryCode, strongSelf.phoneNumberTextField.text];
strongSelf.userModelClass = [[RetrieveDataClass class] retrieveUserInfoForPhoneNumber:PhoneNumberWithIsoCountryCode];
if ([strongSelf.userModelClass.phone_number length] != 0) {
strongSelf.phoneNumber = strongSelf.userModelClass.phone_number;
strongSelf.password = strongSelf.userModelClass.password;
isThisPhoneNumberRegistered = YES;
[strongSelf.activityIndicator stopAnimating];
}
});
});
return isThisPhoneNumberRegistered;
}
The activityIndicator is showing perfectly, but it always return isThisPhoneNumberRegistered = NO, because it works asynchronize way, where my update isThisPhoneNumberRegistered = YES return lately.
So If I want, this scenario where:
User press Sign In button
Then the activityIndicator shows up
My server call (strongSelf.userModelClass = [[RetrieveDataClass class] retrieveUserInfoForPhoneNumber:PhoneNumberWithIsoCountryCode];) retrieve data and set isThisPhoneNumberRegistered = YES or isThisPhoneNumberRegistered = NO according to it
Then return the value to If else condition
if ([self alreadyRegisteredPhoneNumber] == YES) {
if ([self.password isEqualToString:self.passwordTextField.text]) {
[self goToHomeViewController];
} else {
[self initializeAlertControllerForOneButtonWithTitle:#"Wrong Password!" withMessage:kWrongPasswordMSG withYesButtonTitle:#"Ok" withYesButtonAction:nil];
}
How can I do it?
A lot of Thanks in advance.

In general, you want to use Asynch processes so you can "do other stuff" such as updating the UI to let the user know something is going on.
In order to do that, you need to separate your logic. Try to think of it in these terms:
signInButtonAction {
if no phone or password entered
show alert
else
showAnimatedSpinner()
checkForRegisteredPhone()
}
checkForRegisteredPhone {
// start your async check phone number process
// on return from the async call,
if !registered
hide spinner
show kSignInPhoneNumberDoesnotExistMSG message
else
checkForMatchingPassword()
}
checkForMatchingPassword {
if !passwordsMatch
hide spinner
show "passwords don't match" message
else
hide spinner
goToHomeViewController
}
In other words, don't write your code so it gets "locked into" a process, preventing anything else from happening.

Related

Problems on updating UI from async callback

I have the following code :
#property (weak, nonatomic) IBOutlet UIView *loadingView;
-(void) hideLoadingScreen{
self.loadingViewRect = self.loadingView.frame;
[self.loadingView setHidden:YES];
[self.loadingView setFrame:CGRectMake(0,0,0,0)];
}
- (void)viewDidAppear:(BOOL)animated{
[self.apiClient checkLoggedInWithCallback:^(int status){
if(status == ONLINE_LOGGED_IN){
[self.dbAPI isPullSynchronized:^(BOOL isPullSynced){
if(isPullSynced){
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
[self hideLoadingScreen];
} else {
[self.apiClient getTodayVisits:^(NSArray* visits){
[self.dbAPI insertTodayVisits:visits withCallback:^(int status){
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
}];
}];
}
}];
} else if(status == ONLINE_NOT_LOGGED_IN || status == ONLINE_INVALID_TOKEN || status == OFFLINE_NOT_LOGGED_IN) {
//Redirect to login
} else {
//Get from Local DB
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
}
}];
}
The hideLoadingScreen method won't execute (I mean it gets executed, but the UI doesn't update).
I tried all things to make it work (including dispatching [self hideLoadingScreen] to the main thread via GCD and performSelectorOnMainThread / making a __block BOOL variable isLoading and sleeping on the main thread till that variable was changed etc.). I also called the hideLoadingView method on the viewDidAppear method and it works, but I want it to hide when the callback is executed. Unfortunately, I couldn't find a solution by searching on stackoverflow, neither on google (I must say I tried all the solutions I found).
L.E. I logged self.loadingView as Rob Napier suggested
New code:
-(void) hideLoadingScreen{
self.loadingViewRect = self.loadingView.frame;
NSLog(#"hideLoadingScreen before: %#",self.loadingView);
[self.loadingView setHidden:YES];
[self.loadingView setFrame:CGRectMake(0,0,0,0)];
NSLog(#"hideLoadingScreen after: %#",self.loadingView);
}
- (void)viewDidAppear:(BOOL)animated{
NSLog(#"%#",self.loadingView);
[self.apiClient checkLoggedInWithCallback:^(int status){
if(status == ONLINE_LOGGED_IN){
[self.dbAPI isPullSynchronized:^(BOOL isPullSynced){
if(isPullSynced){
dispatch_async(dispatch_get_main_queue(), ^{
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
NSLog(#"async before: %#",self.loadingView);
[self hideLoadingScreen];
NSLog(#"async after: %#",self.loadingView);
});
} else {
[self.apiClient getTodayVisits:^(NSArray* visits){
[self.dbAPI insertTodayVisits:visits withCallback:^(int status){
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
}];
}];
}
}];
} else if(status == ONLINE_NOT_LOGGED_IN || status == ONLINE_INVALID_TOKEN || status == OFFLINE_NOT_LOGGED_IN) {
//Redirect to login
} else {
//Get from Local DB
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
}
}];
}
Logs:
2016-01-08 16:22:25.973 sunwaves.reporting[4566:282042] async before: <UIView: 0x7fa681e745d0; frame = (0 0; 1024 650); autoresize = RM+H+BM; layer = <CALayer: 0x7fa681e291c0>>
2016-01-08 16:22:25.973 sunwaves.reporting[4566:282042] hideLoadingScreen before: <UIView: 0x7fa681e745d0; frame = (0 0; 1024 650); autoresize = RM+H+BM; layer = <CALayer: 0x7fa681e291c0>>
2016-01-08 16:22:25.974 sunwaves.reporting[4566:282042] hideLoadingScreen after: <UIView: 0x7fa681e745d0; frame = (0 0; 0 0); hidden = YES; autoresize = RM+H+BM; layer = <CALayer: 0x7fa681e291c0>>
2016-01-08 16:22:25.974 sunwaves.reporting[4566:282042] async after: <UIView: 0x7fa681e745d0; frame = (0 0; 0 0); hidden = YES; autoresize = RM+H+BM; layer = <CALayer: 0x7fa681e291c0>>
The majority of UIKit calls must be made on the main queue. You should use dispatch_async(dispatch_get_main_queue(),... to do this.
This includes your calls to reloadData at a minimum.
You assignments to self.data are also likely not thread-safe (unless you've done something special in the setter). So those need to be on the main queue.
And of course your calls to hideLoadingScreen.
I assume that most of these blocks execute off the main queue, so that means putting in dispatch_async in several places.
- (void)viewDidAppear:(BOOL)animated{
[self.apiClient checkLoggedInWithCallback:^(int status){
if(status == ONLINE_LOGGED_IN){
[self.dbAPI isPullSynchronized:^(BOOL isPullSynced){
if(isPullSynced){
dispatch_async(dispatch_get_main_queue(), ^{
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
[self hideLoadingScreen];
});
} else {
[self.apiClient getTodayVisits:^(NSArray* visits){
[self.dbAPI insertTodayVisits:visits withCallback:^(int status){
dispatch_async(dispatch_get_main_queue(), ^{
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
});
}];
}];
}
}];
} else if(status == ONLINE_NOT_LOGGED_IN || status == ONLINE_INVALID_TOKEN || status == OFFLINE_NOT_LOGGED_IN) {
//Redirect to login
} else {
//Get from Local DB
dispatch_async(dispatch_get_main_queue(), ^{
self.data = [self.dbAPI getTodayVisits];
[[self tableView] reloadData];
});
}
}];
}

CBLQueryEnumerator count returns nil for first time, second time works correct

when I launch App for first time (App is not installed perviously) on simulator, the instance of CBLQueryEnumerator count returns nil.
I found it by placing breakpoints and executing
po enumeratorResult
but the enumerator object seems to be allocated.
When I launch App for second time (in this case App is already installed on simulator) the instance of CBLQueryEnumerator count returns 5 (I have 5 documents in DB).
Am I making mistake in using CBLQuery or CBLQueryEnumerator please guide me correct.
viewContoller.m
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.progressView.progressViewStyle = UIProgressViewStyleBar;
[self.progressView setProgress:2.5 animated:YES];
self.cbObject = [CouchBaseObject sharedInstance];
self.syncURLLabel.text = [NSString stringWithFormat:#"%#",self.cbObject.syncURL];
self.documentList = [NSMutableArray array];
[self addDocumentToTicketModel:self.cbObject.database];
if(self.cbObject.pull.status == kCBLReplicationOffline || self.cbObject.pull.status != kCBLReplicationActive){
[self performSelector:#selector(pushTicketDetailViewController) withObject:self afterDelay:2.5];
}
}
-(void)addDocumentToTicketModel:(CBLDatabase*)database{
CBLView* view = [database viewNamed:#"_temp_view"];
if (!view.mapBlock) {
[view setMapBlock:MAPBLOCK({
if (doc) {
emit(doc,#"1");
}
})version:#"1.0"];
}
CBLQuery* query = [view createQuery];
[query runAsync:^(CBLQueryEnumerator * enumeratorResult, NSError * error) {
if(!error){
for (CBLQueryRow* row in enumeratorResult) {
CBLDocument* document = [database documentWithID:row.documentID];
Ticket* ticket = [Ticket modelForDocument:document];
NSLog(#"Ticket ; %#",ticket.propertiesToSave);
[self.documentList addObject:ticket];
}
}
}];
}
#end
CouchBaseObject.m
#implementation CouchBaseObject
-(instancetype)init{
self = [super init];
if(self){
NSError* error;
self.manager = [CBLManager sharedInstance];
if(!self.manager){
NSLog(#"manager fail");
return nil;
}
self.database = [self.manager databaseNamed:#"couch_sample_one" error:&error];
if(!self.database){
NSLog(#"database fail");
return nil;
}
[self initReplication];
}
return self;
}
+(CouchBaseObject*)sharedInstance{
static CouchBaseObject* sharedInstance = nil;
if(sharedInstance == nil){
sharedInstance = [[CouchBaseObject alloc]init];
}
return sharedInstance;
}
-(void)initReplication{
self.syncURL = [[NSURL alloc]initWithString:#"http://***.***.***.***:5984/couch_sample_one"];
self.pull = [self.database createPullReplication:self.syncURL];
self.push = [self.database createPushReplication:self.syncURL];
self.pull.continuous = NO;
self.push.continuous = NO;
[self startReplication];
}
-(void)startReplication{
[self.push start];
[self.pull start];
}
-(void)stopReplication{
[self.push stop];
[self.pull stop];
}
#end
For first time the control will not enter into for in loop
for (CBLQueryRow* row in result)
and for second time control will be in that loop.
This also happens when on just on launch.
Scenario.
Run App (Freshly installed app)
Navigate from initialViewController to viewController.
First time control does not enter into for loop, CBLQueryEnumerator Object.count returns nil.
pop to initialViewController
Push viewController, but this time controls enter into for in loop and CBLQueryEnumerator object.count returns 5
Hierarchy (Push).
initialViewContoller -> ViewContoller -> ListViewController

ReactiveCocoa takeUntil 2 possible signals?

So I have successfully turned a button into an off and on switch that changes the label.
I was also able to have it start a timed processed set off when that is to occur, and it have the ability to shut off the timed process.
Anyways I need to way to shut down the timed process I was wondering if there was a way to stop it without using the disposable. With a second takeUntil signal.
Edit I think what I was trying to do was slightly misleading let me show my current solution that works.
-(RACSignal*) startTimer {
return [[RACSignal interval:1.0
onScheduler:[RACScheduler mainThreadScheduler]]
startWith:[NSDate date]];
}
-(void) viewWillAppear:(BOOL)animated {}
-(void) viewDidLoad {
self.tableView.delegate = self;
self.tableView.dataSource = self;
RACSignal* pressedStart = [self.start rac_signalForControlEvents:UIControlEventTouchUpInside];
#weakify(self);
RACSignal* textChangeSignal = [pressedStart map:^id(id value) {
#strongify(self);
return [self.start.titleLabel.text isEqualToString:#"Start"] ? #"Stop" : #"Start";
}];
// Changes the title
[textChangeSignal subscribeNext:^(NSString* text) {
#strongify(self);
[self.start setTitle:text forState:UIControlStateNormal];
}];
RACSignal* switchSignal = [[textChangeSignal map:^id(NSString* string) {
return [string isEqualToString:#"Stop"] ? #0 : #1;
}] filter:^BOOL(id value) {
NSLog(#"Switch %#",value);
return [value boolValue];
}];
[[self rac_signalForSelector:#selector(viewWillAppear:)]
subscribeNext:^(id x) {
}];
static NSInteger t = 0;
// Remake's it self once it is on finished.
self.disposable = [[[textChangeSignal filter:^BOOL(NSString* text) {
return [text isEqualToString:#"Stop"] ? [#1 boolValue] : [#0 boolValue];
}]
flattenMap:^RACStream *(id value) {
NSLog(#"Made new Sheduler");
#strongify(self);
return [[self startTimer] takeUntil:switchSignal];
}] subscribeNext:^(id x) {
NSLog(#"%#",x);
#strongify(self);
t = t + 1;
NSLog(#"%zd",t);
[self updateTable];
}];
[[self rac_signalForSelector:#selector(viewWillDisappear:)] subscribeNext:^(id x) {
NSLog(#"viewWillAppear Dispose");
[self.disposable dispose];
}];
}
-(BOOL) isGroupedExcercisesLeft {
BOOL isGroupedLeft = NO;
for (int i =0;i < [self.excercises count]; i++) {
Excercise* ex = [self.excercises objectAtIndex:i];
if(ex.complete == NO && ex.grouped == YES) {
isGroupedLeft = YES;
break;
}
}
return isGroupedLeft;
}
-(void) updateTable {
// Find the
NSInteger nextRow;
if (([self.excercises count] > 0 || self.excercises !=nil) && [self isGroupedExcercisesLeft]) {
for (int i =0;i < [self.excercises count]; i++) {
Excercise* ex = [self.excercises objectAtIndex:i];
if(ex.complete == NO && ex.grouped == YES) {
nextRow = i;
break;
}
}
NSIndexPath* path = [NSIndexPath indexPathForItem:nextRow inSection:0];
NSArray* indexPath = #[path];
// update //
Excercise* ex = [self.excercises objectAtIndex:nextRow];
[self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
if (ex.seconds <= 0) {
RLMRealm* db = [RLMRealm defaultRealm];
[db beginWriteTransaction];
ex.complete = YES;
[db commitWriteTransaction];
}
else {
// Update Seconds
RLMRealm* db = [RLMRealm defaultRealm];
[db beginWriteTransaction];
ex.seconds = ex.seconds - 1000;
NSLog(#"Seconds: %zd",ex.seconds);
[db commitWriteTransaction];
// Update table
[self.tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationNone];
}
} else {
NSLog(#"Done");
SIAlertView *alertView = [[SIAlertView alloc] initWithTitle:#"Deskercise" andMessage:#"Excercises Complete"];
[alertView addButtonWithTitle:#"Ok"
type:SIAlertViewButtonTypeDefault
handler:^(SIAlertView *alert) {
}];
alertView.transitionStyle = SIAlertViewTransitionStyleBounce;
[alertView show];
NSLog(#"Dispose");
[self.disposable dispose];
}
}
The issue with using takeUntil:self.completeSignal is that when you change completeSignal to another value, it isn't passed to any function that was already waiting for the variable that completeSignal was previously holding.
- (RACSignal*) startTimer {
#weakify(self)
return [[[RACSignal interval:1.0
onScheduler:[RACScheduler mainThreadScheduler]]
startWith:[NSDate date]]
takeUntil:[[self.start rac_signalForControlEvents:UIControlEventTouchUpInside]
merge:[[RACObserve(self, completeSignal) skip:1] flattenMap:
^RACStream *(RACSignal * signal) {
#strongify(self)
return self.completeSignal;
}]]
];
}
The signal is now observing and flattening completeSignal, which will give the desired effect. Signals that complete without sending next events are ignored by takeUntil:, so use self.completedSignal = [RACSignal return:nil], which sends a single next event and then completes.
However, this code is anything but ideal, let's look at a better solution.
#property (nonatomic, readwrite) RACSubject * completeSignal;
- (RACSignal*) startTimer {
return [[[RACSignal interval:1.0
onScheduler:[RACScheduler mainThreadScheduler]]
startWith:[NSDate date]]
takeUntil:[[self.start rac_signalForControlEvents:UIControlEventTouchUpInside]
merge:self.completeSignal]
];
}
- (void) viewDidLoad {
[super viewDidLoad];
self.completeSignal = [RACSubject subject];
self.tableView.delegate = self;
self.tableView.dataSource = self;
RACSignal * pressedStart = [self.start rac_signalForControlEvents:UIControlEventTouchUpInside];
#weakify(self);
RACSignal* textChangeSignal = [[pressedStart startWith:nil] scanWithStart:#"Stop" reduce:^id(id running, id next) {
return #{#"Start":#"Stop", #"Stop":#"Start"}[running];
}];
[self.start
rac_liftSelector:#selector(setTitle:forState:)
withSignals:textChangeSignal, [RACSignal return:#(UIControlStateNormal)], nil];
[[[pressedStart flattenMap:^RACStream *(id value) { //Using take:1 so that it doesn't get into a feedback loop
#strongify(self);
return [self startTimer];
}] scanWithStart:#0 reduce:^id(NSNumber * running, NSNumber * next) {
return #(running.unsignedIntegerValue + 1);
}] subscribeNext:^(id x) {
#strongify(self);
[self updateTable];
NSLog(#"%#", x);
}];
}
- (void) updateTable {
//If you uncomment these then it'll cause a feedback loop for the signal that calls updateTable
//[self.start sendActionsForControlEvents:UIControlEventTouchUpInside];
//[self.completeSignal sendNext:nil];
if ([self.excercises count] > 0 || self.excercises !=nil) {
} else {
}
}
Let's run through the list of changes:
completeSignal is now a RACSubject (a manually controlled RACSignal).
For purity and to get rid of the #weakify directive, textChangeSignal now uses the handy scanWithStart:reduce: method, which lets you access an accumulator (this works well for methods that work with an incrementing or decrementing number).
start's text is now being changed by the rac_liftSelector function, which takes RACSignals and unwraps them when all have fired.
Your flattenMap: to replace pressedStart with [self startTimer] now uses scanWithStart:reduce, which is a much more functional way to keep count.
I'm not sure if you were testing by having updateTable contain completion signals but it definitely causes a logic issue with your flattenMap: of pressedButton, the resulting feedback loop eventually crashes the program when the stack overflows.

Disable (login)button when logging in

Hello i'm working on this app which has a login section. What i want is when i click the login button that button has to be unclickable until the login succeeds or fails. I already tried adding this line doLogin.enabled = NO;
But that wasn't useful. Please help. This is my code:
- (IBAction)doLogin:(id)sender {
[self loginUser];
}
- (void)loginUser
{
if (![self.usernameBox.text isEqualToString:#""] && ![self.passwordBox.text isEqualToString:#""])
{
//TODO: check id email pattern is correct
[self showLoginProcess:true];
[[AuthSingleton getInstance] attemptLoginWithUsername:self.usernameBox.text andPassword:self.passwordBox.text withSuccesBlock:^(AFHTTPRequestOperation *operation, id responseObject)
{
[self showLoginProcess:false];
UIViewController *newFrontController = nil;
PaMapViewController * vc = [[PaMapViewController alloc] init];
newFrontController = [[UINavigationController alloc] initWithRootViewController:vc];
SWRevealViewController *revealController = self.revealViewController;
[revealController pushFrontViewController:newFrontController animated:YES];
} andFailureBlock:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSDictionary *dic = [error.userInfo objectForKey:#"JSONResponseSerializerWithDataKey"];
#ifdef DEBUG
NSLog(#"dic = %#", dic);
#endif
if ([[dic objectForKey:#"error_uri"] isEqual:#"phone"])
{
NSError *jsonError;
NSData *objectData = [[dic objectForKey:#"error_description"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
[self loginFailed:json];
}
else
{
[self loginFailed:dic];
}
}];
}
else
{
//TODO: show proper message Test
NSLog(#"username or password is empty %#", kBaseURL);
}
}
- (void)showLoginProcess:(BOOL) show
{
[self.spinner setColor:[UIColor whiteColor]];
self.spinner.hidden = !show;
self.usernameBox.hidden = show;
self.passwordBox.hidden = show;
if (show)
{
[self.spinner startAnimating];
} else
{
[self.spinner stopAnimating];
}
}
Hope you have declared a property for the login button. Let it be "doLogin".
What you need to do is
- (IBAction)doLogin:(id)sender
{
[self loginUser];
doLogin.userInteractionEnabled = NO;
}
and when login succeeds or fails write
doLogin.userInteractionEnabled = YES;
within the corresponding block.
Instead of
doLogin.enabled = NO
write
doLogin.userInteractionEnabled = NO
- (IBAction)doLogin:(id)sender
{
doLogin.userInteractionEnabled = NO;
[self loginUser];
doLogin.userInteractionEnabled = YES;
}
Given below is the code snipe that should help
- (IBAction)loginUser:(id)sender
{
//before login disable the user interaction of the button
loginButton.userInteractionEnabled = NO;
/*Your login logic here*/
// after successful login enable the login button once again
loginButton.userInteractionEnabled = YES;
}

Can an asynchronous task be run in a loop? (in iOS)

basically I'm using firebase to query a user's 'status' property and doing so in a do/while loop.
If the status property is free then i want to break the loop and continue with the rest of the method. If the status property is not free then I want to query firebase again for a new user until a free user is found.
My firebase code works fine outside the loop but doesn't seem to be called inside of it. Here is the loop:
__block uint32_t rando;
self.freedom = #"about to check";
do {
//check if free
[self checkIfFree:^(BOOL finished) {
if (finished) {
if ([self.freedom isEqualToString:#"free"]) {
//should break loop here
}
else if ([self.freedom isEqualToString:#"matched"]){
//get another user
do {
//picking another random user from array
rando = arc4random_uniform(arraycount);
}
while (rando == randomIndex && rando == [self.randString intValue]);
self.randString = [NSString stringWithFormat:#"%u", rando];
[users removeAllObjects];
[users addObject:[usersArray objectAtIndex:rando]];
self.freeUser = [users objectAtIndex:0];
//should repeat check here but doesn't work
}
else{
NSLog(#"error!");
}
}
else{
NSLog(#"not finished the checking yet");
}
}];
} while (![self.freedom isEqual: #"free"]);
And here's my firebase code:
-(void)checkIfFree:(myCompletion) compblock{
self.freeUserFB = [[Firebase alloc] initWithUrl:[NSString stringWithFormat: #"https://skipchat.firebaseio.com/users/%#", self.freeUser.objectId]];
[self.freeUserFB observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot)
{
self.otherStatus = snapshot.value[#"status"];
NSLog(#"snapshot info %#", snapshot.value);
if ([self.otherStatus isEqualToString:#"free"]) {
self.userIsFree = YES;
self.freedom = #"free";
}
else{
self.userIsFree = NO;
self.freedom = #"matched";
}
compblock(YES);
}];
}
Thanks!
I am not sure I understand correctly your question.
If you want to run your completion code again till some condition is matched (in this case [self.freedom isEqualToString:#"free"]) you can do the following (removing the do - while):
void( ^ myResponseBlock)(BOOL finished) = ^ void(BOOL finished) {
if (finished) {
if ([self.freedom isEqualToString: #"free"]) {
return;
} else if ([self.freedom isEqualToString: #"matched"]) {
//get another user
do {
//picking another random user from array
rando = arc4random_uniform(arraycount);
}
while (rando == randomIndex && rando == [self.randString intValue]);
self.randString = [NSString stringWithFormat: #"%u", rando];
[users removeAllObjects];
[users addObject:usersArray[rando]];
self.freeUser = users.firstObject;
// Schedule another async check
[self checkIfFree: myResponseBlock];
} else {
NSLog(#"error!");
}
} else {
NSLog(#"not finished the checking yet");
}
};
[self checkIfFree: myResponseBlock];

Resources