在调用Web服务时显示UIActivityIndi​​cator

时间:2014-01-06 06:19:57

标签: ios objective-c uiactivityindicatorview

我需要在等待来自Web服务的响应时显示UIActivityIndi​​cator。我到底把它的代码放在哪里?它没有这种方式。活动指标未显示。

我是否需要使用异步请求才能显示它?

    -(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 {

        }
    }

3 个答案:

答案 0 :(得分:3)

是的,问题是Synchronous请求。

如果可以发送ASynchronous请求,那么请尝试这样做。

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

// stop activity

// write other code you want to execute

}];

答案 1 :(得分:0)

我发现MBProgressHUD是最佳指标,你可以使用它只是在你的方法调用的开始就像

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];
});

并在你的finally块中你可以隐藏这个

    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD hide:YES];
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    });

答案 2 :(得分:0)

//.h file
@interface ViewController : UIViewController
{
UIActivityIndicatorView *activityIndicator;
BOOL showingActivityIndicator;
}
@property(nonatomic) BOOL showingActivityIndicator;
@property(nonatomic) UIActivityIndicatorView *activityIndicator;
@end


//.m file

@synthesize  showingActivityIndicator,activityIndicator;

/////在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];
    }