Search code examples
iosiphoneios6

How to show loading view controller in my webservices


I want to show a loading view controller or activity indicator view when I call my loginUserintoserver method but while debugging I found the view becomes inactive at this line.

 NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil]; 

For sometime till I get the response. I have tried showing activity indicators but did not succeed. Please any guidelines to resolve this. Thanks in advance.

-(void) loginUserintoserver

{

NSString *str_validateURL = @"callogin";

// em,password,devicereg,devicetype,flag = ("e" or "m")

NSString *str_completeURL = [NSString stringWithFormat:@"%@%@", str_global_domain, str_validateURL];
NSURL *url = [NSURL URLWithString:str_completeURL];


NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];

[theRequest setHTTPMethod:@"POST"];

[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

str_global_UserPhone = [NSString stringWithFormat:@"%@%@",signupCountryCodeTextField.text,signupMobileTextField.text];

NSString *postData = [NSString stringWithFormat:@"em=%@&password=%@&devicereg=%@&devicetype=%@&flag=%@", loginEmailTextField.text, loginPasswordTextField.text, str_global_DeviceRegID, @"1", [NSString stringWithFormat:@"%@", emailphoneFlag]];

NSLog(@"==============%@",postData);
NSString *length = [NSString stringWithFormat:@"%d", [postData length]];

[theRequest setValue:length forHTTPHeaderField:@"Content-Length"];

[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];

// here the view becomes inactive and takes time to get response from server

NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSLog(@"response data is %@", responseData);

if (responseData == nil)
{
    NSLog(@"No data from server");

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:@"No data downloaded from server!"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
    [alertView show];

}
else
{
    NSLog(@"response data is %@", responseData);
    NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"returnString....%@",returnString);

    NSDictionary *response_dic = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];

    NSString *msg;
    msg = [response_dic objectForKey:@"Result"];
    NSDictionary *loginDict=[[NSDictionary alloc]init];
    loginDict=[response_dic objectForKey:@"Result"];
    NSLog(@"msg is  : %@ ",[response_dic objectForKey:@"Result"]);

    if ([[[response_dic objectForKey:@"Result"] objectForKey:@"ErrorCode"] isEqualToString:@"0"])
    {
        // success
        NSLog(@"Successfull Login!!!!!");

        NSString *UserId=[loginDict objectForKey:@"userid"];
        [[NSUserDefaults standardUserDefaults] setValue:UserId  forKey:@"LoginId"];

        [self initRevealViewController];


    } else if ([[[response_dic objectForKey:@"Result"] objectForKey:@"ErrorCode"] isEqualToString:@"1"]){
        NSLog(@"Invalid Password!");

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message: @"ReEnter Password" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];


    }else if ([[[response_dic objectForKey:@"Result"] objectForKey:@"ErrorCode"] isEqualToString:@"3"]){
        NSLog(@"Invalid input parameters!");

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message: @"Email address or Mobile number, Password, devicereg, devicetype, flag are Mandatory" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];


    }else if ([[[response_dic objectForKey:@"Result"] objectForKey:@"ErrorCode"] isEqualToString:@"6"]){
        NSLog(@"Invalid input parameters!");

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message: @"User Registered but not activated" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];

    }
}
}

Solution

  • Most of the answers are partial which do not point out the main issue in your code.

    Synchronous request on main thread will block it, thus you cannot show any UI updates like activity indicator while the sync request is in progress. Instead make asynchronous request (or make request in background using GCD) and use UIActivityIndicatorView or any other open source available for this.

    Follow this Q&A to learn how to make asyn request using GCD: NSURLConnection and grand central dispatch

    You can create and add an activity indicator to the view. Present and start showing activity when request is initiated and stop the activity when request completes downloading.

    Hope that helps!