user6385712
user6385712

Reputation:

Use of activity indicator in json parsing

I am working on application and i have to use activityindicator when login is in progress, i am not getting where i have to use the code for activityindicator in the below code:-

- (IBAction)Login:(id)sender
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl@"login"]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

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


    [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

    NSString *mapData = [NSString stringWithFormat:@"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];

    NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if(error == nil)
        {

            NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
            NSLog(@"text= %@",text);

            NSError *error = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if(error!=nil)
            {
                NSLog(@"error = %@",error);

            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [self checkUserSuccessfulLogin:json];
            });
        }
        else{

            NSLog(@"Error : %@",error.description);

        }


    }];


    [postDataTask resume];




}

It is taking time to go the other page after login. please help me.

Upvotes: 0

Views: 611

Answers (5)

Milan Vadgama
Milan Vadgama

Reputation: 321

Try This Code

-(IBAction)Login:(id)sender
{

    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGRect activityFrame = CGRectMake(130,10,40,40);
    [activityView setFrame: activityFrame];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:activityView];
        activityView.center = self.view.center;
        [activityView startAnimating];
        [self.view bringSubviewToFront:activityView];

    });

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl@"login"]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

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


    [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

    NSString *mapData = [NSString stringWithFormat:@"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];

    NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if(error == nil)
        {

            NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
            NSLog(@"text= %@",text);

            NSError *error = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            if(error!=nil)
            {
                NSLog(@"error = %@",error);

            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [activityView stopAnimating];
             [activityView removeFromSuperview];
                [self checkUserSuccessfulLogin:json];
            });
        }
        else{

            NSLog(@"Error : %@",error.description);

        }


    }];


    [postDataTask resume];




}

Upvotes: 0

Ketan Parmar
Ketan Parmar

Reputation: 27438

 - (IBAction)Login:(id)sender

 {
//show or add youar activity indicator here


NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl@"login"]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

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


[request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];

NSString *mapData = [NSString stringWithFormat:@"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];

NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    //Hide or remove your activity indicator here


    if(error == nil)
    {

        NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
        NSLog(@"text= %@",text);

        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        if(error!=nil)
        {
            NSLog(@"error = %@",error);

        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [self checkUserSuccessfulLogin:json];
        });
    }
    else{

        NSLog(@"Error : %@",error.description);

    }


}];


[postDataTask resume];




}

As i add comments in your code, show your activity indicator at very start of method as user tap button it starts and hide it from completion handler because completion handler calls after response is came from server.

Hope this will help :)

Upvotes: 0

Santo
Santo

Reputation: 1651

Use this below code

//main thread
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);

//if you want to add to window, use this below one
[appdelegate.window addSubview:spinner];

//or if you want to add to view, use below one
 [self.view addSubView:spinner];

[spinner startAnimating];


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),^{

    dispatch_async(dispatch_get_main_queue(), ^{

   //after your server call or parsing or something you can call this to stop animating 

   [spinner stopAnimating];
  });
  });

Upvotes: 1

Parth Patel
Parth Patel

Reputation: 1290

I have updated code for Activity indicator.

Just make the outlet of the Activity Indicator in .h file.

@property (weak,nonatomic) UIActivityIndicatorView *indicator;

then, write below code in .m file's viewDidLoad().

self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.indicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);

Below is the code for Json parsing:

- (IBAction)Login:(id)sender
{

    [self.indicator startAnimating];//The ActivityIndicator Starts Animating Here

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl@"login"]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

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


    [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

    NSString *mapData = [NSString stringWithFormat:@"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];

    NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if(error == nil)
    {
        dispatch_async(dispatch_get_main_queue(), ^{

             [self.indicator stopAnimating];//The ActivityIndicator Stops Animating when Response Arrives

             NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
             NSLog(@"text= %@",text);

             NSError *error = nil;
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

             [self checkUserSuccessfulLogin:json];
        });
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{

             [self.indicator stopAnimating];
        });
        NSLog(@"Error : %@",error.description);
    }
 }];

 [postDataTask resume];

}

Upvotes: 0

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

aakash,

You can make use of MBProgressHUD third party framework you need not write the code for activity inddicator adding it to screen and all (no need to re invent the wheel) here is a link :) https://github.com/jdg/MBProgressHUD

add a pod dependency or add the files to your project however you feel comfortable.

import files.

#import <MBProgressHUD/MBProgressHUD.h>

    - (IBAction)Login:(id)sender
    {
        //add the MBProgressHud here before you make the webservice call
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        hud.labelText = NSLocalizedString(@"Login in progress", nil);

        [self.navigationController.view addSubview:self.HUD];

        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl@"login"]];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:60.0];

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


        [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

        [request setHTTPMethod:@"POST"];

        NSString *mapData = [NSString stringWithFormat:@"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];

        NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        [request setHTTPBody:postData];


        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
            //finally hide it, whether its sucess or failure just remove it 
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            });
            if(error == nil)
            {

                NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                NSLog(@"text= %@",text);

                NSError *error = nil;
                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

                if(error!=nil)
                {
                    NSLog(@"error = %@",error);

                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    [self checkUserSuccessfulLogin:json];
                });
            }
            else{

                NSLog(@"Error : %@",error.description);

            }


        }];


        [postDataTask resume];
}

Upvotes: 0

Related Questions