Question

I need to show a UIActivityIndicator while i am waiting for response from the web service. Where exactly do i put the code for it?? It does not work this way. the activity indicator does not show up.

Do i need to use asynchronous request in order to show it??

    -(void)callWebService
    {
        [self.customercareSearchbar resignFirstResponder];
        [self.SRResultDictionary removeAllObjects];
        NSLog(@"web service called");
        NSString *srn = _SRNumber;
        NSString *serviceURL = [NSString stringWithFormat:@"https://abcdef...];

        @try {
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                [self.view addSubview:activity];

                activity.center = self.view.center;
                [self.view bringSubviewToFront:loadView];
                activity.hidesWhenStopped = YES;
                [activity setHidden:NO];

                [activity startAnimating];

            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
            NSURLResponse *serviceResponse = nil;
            NSError *err = nil;

            NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];

            [activity stopAnimating];

            NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];

            if(!parsedData)
            {
                NSLog(@"data not parsed");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                [alert show];
                [self.customerCareTableView setHidden:YES];
            }
            else
            {
                NSLog(@"parsed");
                NSLog(@"parsed.. the size is %lu", (unsigned long)[parsedData count]);
                NSLog(@"%@", parsedData);

                NSString *status = [parsedData objectForKey:@"ns:Status"];
                NSLog(@"the status is %@", status);
                if([status isEqualToString:@"Success"])
                {
                    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

                    if([[prefs objectForKey:@"SwitchState"] isEqualToString:@"OFF"])
                    {
                        //do nothing
                    }

                    else
                    {
                        [self saveNumberInDatabase:srn];
                    }

                    NSMutableDictionary *third = [parsedData objectForKey:@"ListOfXrxLvServiceRequest"];
                    NSLog(@"internal dict is %@", third);

                    self.SRResultDictionary = [third objectForKey:@"ServiceRequest"];

                    [self.customerCareTableView reloadData];
                    [self.customerCareTableView setHidden:NO];
                }

                else if([status isEqualToString:@"Record Not Found"])
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid Entry" message:@"Please enter a valid Service Request Number" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [alert show];
                    [self.customerCareTableView setHidden:YES];
                }

                else
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                    [alert show];
                    [self.customerCareTableView setHidden:YES];
                }
            }
        }

        @catch (NSException *exception)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:@"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [self.customerCareTableView setHidden:YES];
        }
        @finally {

        }
    }
Was it helpful?

Solution

Yes, problem is the Synchronous request.

If it is fine to send ASynchronous request then try doing this.

[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

// stop activity

// write other code you want to execute

}];

OTHER TIPS

I found MBProgressHUD is best indicator and you can use is simply in your starting of method call like

dispatch_async(dispatch_get_main_queue(), ^{
    if(!HUD) HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.view addSubview:HUD];
    HUD.delegate = self;
    HUD.userInteractionEnabled = NO;
    HUD.labelText = @"Saving your Preferences...";
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [HUD show:YES];
});

and in your finally block you can hide this like

    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD hide:YES];
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    });
//.h file
@interface ViewController : UIViewController
{
UIActivityIndicatorView *activityIndicator;
BOOL showingActivityIndicator;
}
@property(nonatomic) BOOL showingActivityIndicator;
@property(nonatomic) UIActivityIndicatorView *activityIndicator;
@end


//.m file

@synthesize  showingActivityIndicator,activityIndicator;

///// Call this method in viewDidLoad

 -(void)initializeClass     
 {    
     self.activityIndicator = [[UIActivityIndicatorView alloc]  initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];   

    self.activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;  

    self.activityIndicator.hidesWhenStopped = YES;   
    [self layoutSubviews];    
    }

    -(void)layoutSubviews
    {
    CGRect activityIndicatorFrame = self.activityIndicator.frame;  
    activityIndicatorFrame.origin.x = (self.view.frame.size.width - self.activityIndicator.frame.size.width) / 2;
    activityIndicatorFrame.origin.y = (self.view.frame.size.height - self.activityIndicator.frame.size.height) / 2;
    self.activityIndicator.frame = activityIndicatorFrame;

    [self.view addSubview:self.activityIndicator];
    }


    -(void)setShowingActivityIndicator:(BOOL)showingActivityIndicators
     {
    if (showingActivityIndicators) {
        [self.activityIndicator startAnimating];
    } else {
        [self.activityIndicator stopAnimating];
    }
    showingActivityIndicator= showingActivityIndicators;

    }
    -(void)dummyButtonAction  // you button action to call service
    {
    [self setShowingActivityIndicator:YES];
    [self performSelector:@selector(callWebService) withObject:nil afterDelay:0.3];
    //    [self callWebService];
    }

    -(void)callWebService
    {
    [self.view endEditing:YES]; // this statement will make sure keyboard is resigned
    //[self.SRResultDictionary removeAllObjects];
    NSLog(@"web service called");
    NSString *srn = _SRNumber;
    NSString *serviceURL = [NSString stringWithFormat:@"https://abcdef...];

                            @try {


                                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
                                NSURLResponse *serviceResponse = nil;
                                NSError *err = nil;

                                NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];


                                NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];

                                if(!parsedData)
                                {
                                    NSLog(@"data not parsed");
                                    [self ShowAlertViewWithTitleString:@"ERROR":@"Problem in Network. Please Try Again!"];

                                    [self.customerCareTableView setHidden:YES];
                                }
                                else
                                {
                                    NSLog(@"parsed");
                                    NSLog(@"parsed.. the size is %lu", (unsigned long)[parsedData count]);
                                    NSLog(@"%@", parsedData);

                                    NSString *status = [parsedData objectForKey:@"ns:Status"];
                                    NSLog(@"the status is %@", status);
                                    if([status isEqualToString:@"Success"])
                                    {
                                        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

                                        if([[prefs objectForKey:@"SwitchState"] isEqualToString:@"OFF"])
                                        {
                                            //do nothing
                                        }

                                        else
                                        {
                                            [self saveNumberInDatabase:srn];
                                        }

                                        NSMutableDictionary *third = [parsedData objectForKey:@"ListOfXrxLvServiceRequest"];
                                        NSLog(@"internal dict is %@", third);

                                        self.SRResultDictionary = [third objectForKey:@"ServiceRequest"];

                                        [self.customerCareTableView reloadData];
                                        [self.customerCareTableView setHidden:NO];
                                    }

                                    else if([status isEqualToString:@"Record Not Found"])
                                    {

                                        [self ShowAlertViewWithTitleString:@"Invalid Entry":@"Please enter a valid Service Request Number"];

                                        [self.customerCareTableView setHidden:YES];
                                    }

                                    else
                                    {

                                        [self ShowAlertViewWithTitleString:@"ERROR":@"Problem in Network. Please Try Again!"];

                                        [self.customerCareTableView setHidden:YES];
                                    }
                                }
                            }

                            @catch (NSException *exception)
                            {
                                [self ShowAlertViewWithTitleString:@"":@"Problem In Network Connection. Please Try Again!"];
                                [self.customerCareTableView setHidden:YES];
                            }
                            @finally {

                            }

                                [self setShowingActivityIndicator:NO];
    }
    - (void)ShowAlertViewWithTitleString :(NSString *)title :(NSString *)message
    {

      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
      [alert show];
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top