UIActivityIndicatorView startAnimating not working in searchBarSearchButtonClicked

1.8k Views Asked by At

The problem which I can't get through is that the UIActivityIndicatorView in my View doesn't start animating when I execute

[UIActivityIndicatorView startAnimating];

In

searchBarSearchButtonClicked

This is my code:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];

    NSString *causeStr = nil;

    if ([CLLocationManager locationServicesEnabled] == NO)
    {
        causeStr = @"device";
    }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
    {
        causeStr = @"app";
    }
    else
    {
        [_activityIndicatorView startAnimating];

        _searchPlacesResults = [[NSMutableArray alloc] init];

        NSString * searchQuery = [searchBar text];

        FTGooglePlacesAPINearbySearchRequest *request = [[FTGooglePlacesAPINearbySearchRequest alloc] initWithLocationCoordinate:locationManager.location.coordinate];
        request.rankBy = FTGooglePlacesAPIRequestParamRankByDistance;
        request.keyword = searchQuery;
        request.radius = 500;
        [self startSearchingPlaces:request];
    }

    if (causeStr != nil)
    {
        NSString *alertMessage = [NSString stringWithFormat:@"You currently have location services disabled for this %@. Please refer to \"Settings\" app to turn on Location Services.", causeStr];

        [[[UIAlertView alloc] initWithTitle:@"Location Services Disabled"
                                    message:alertMessage
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
}

Nothing happens until I clear the search results from the tableView connected to the UISearchBar using its cancel button.

I have tried and verified that

[UIActivityIndicatorView startAnimating];

actually works when called from other methods.

EDIT: I have also verified that my UIActivityIndicatorView is not null, in fact this is what I get when I NSLog it:

<UIActivityIndicatorView: 0x16e91ed0; frame = (150 274; 20 20); hidden = YES; opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x16e91f90>>
2

There are 2 best solutions below

2
On

You cane use SVProgresshood , a famous class for activity indicator. Download it from here

Copy SVProgressHUD folder to your project.

#import "SVProgressHUD.h"

to your required ViewController.

Where you start to Animate Activity indicator write :

[SVProgressHUD showWithStatus:@"Loading.."];

And where to stop the activity indicator , write :

[SVProgressHUD dismiss];

You can set your own status instead of "Loading.."

Hope it works.

1
On

Did you set a breakpoint to see if the else statement is being called? If so, try the following: set the startAnimating inside the main queue as follows:

dispatch_async(dispatch_get_main_queue(), ^{
    [_activityIndicatorView startAnimating];
});