0

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.

4

5 回答 5

1

使用下面的代码

//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];
  });
  });
于 2016-05-27T07:06:31.880 回答
0

阿卡什,

您可以使用 MBProgressHUD 第三方框架,您无需编写将活动指示器添加到屏幕的代码,所有(无需重新发明轮子)这里是一个链接 :) https://github.com/jdg/MBProgressHUD

添加一个 pod 依赖项或将文件添加到您的项目中,但您感觉很舒服。

导入文件。

#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];
}
于 2016-05-27T06:59:50.637 回答
0

试试这个代码

-(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];




}
于 2016-05-27T07:12:17.193 回答
0

我已经更新了活动指示器的代码。

只需在 .h 文件中制作活动指示器的出口即可。

@property (weak,nonatomic) UIActivityIndicatorView *indicator;

然后,在 .m 文件的 viewDidLoad() 中写入以下代码。

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

下面是Json解析的代码:

- (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];

}
于 2016-05-27T07:04:48.693 回答
0
 - (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];




}

当我在您的代码中添加注释时,在用户点击按钮启动时在方法的最开始显示您的活动指示器并将其隐藏在完成处理程序中,因为完成处理程序在响应来自服务器后调用。

希望这会有所帮助:)

于 2016-05-27T07:21:40.443 回答