【问题标题】:Activity indicator with SBJson framework带有 SBJson 框架的活动指示器
【发布时间】:2013-08-28 04:47:11
【问题描述】:

我目前正在开发一个应用程序,该应用程序使用基本登录页面来检查用户是否有权访问该应用程序。我在this tutorial 的帮助下制作了登录部分,它使用this frame work 来使用来自简单网络脚本的用户名和密码。

我希望其他人可能已经使用它或可以帮助我解决我的问题。我不想显示活动指示器,我使用MBProgressHUD 作为活动指示器。

所以我已经对其进行了试验,但无法让它在应用程序连接到 URL 时显示活动指示器。我用登录过程模拟了一些错误的连接,但是当应用程序连接到 URL 时,活动指示器不会显示。它只显示错误,唯一显示任何类型加载成功的是登录按钮按下状态为“活动”(蓝色突出显示),直到加载完成。

这是我的代码,当用户输入用户名和密码并点击登录按钮时运行:

// Login button
- (IBAction)loginBtnClicked:(id)sender
{
    // Show the activity indicator
    [HUD showUIBlockingIndicatorWithText:@"Loggar in..."];

    @try {
        if([[userNameTxtField text] isEqualToString:@""] || [[passwordTxtField text] isEqualToString:@""] ) {

            // No username or password entered
            [self alertStatus:@"Du måste ange användarnamn och lösenord" :@"Något gick fel!"];

            // Hide activity indicator
            [HUD hideUIBlockingIndicator];

        } else {

            NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[userNameTxtField text],[passwordTxtField text]];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://www.nebulon.se/json/sendus/jsonlogin.php"];

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

            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

            NSLog(@"Response code: %d", [response statusCode]);
            if ([response statusCode] >=200 && [response statusCode] <300){

                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);

                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
                NSLog(@"%d",success);

                if(success == 1){

                    // Login success, grant user access to app
                    NSLog(@"Login SUCCESS");

                    [self loginSuccess];

                    // Hide activity indicator
                    [HUD hideUIBlockingIndicator];

                    // Store username
                    NSString *userName = [userNameTxtField text];
                    NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
                    [UserDefaults setObject:userName forKey:@"userName"];
                    [UserDefaults synchronize];

                    [self dismissViewControllerAnimated:NO completion:nil];

                } else {

                    // Login error
                    NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                    [self alertStatus:error_msg :@"Inloggningen misslyckades"];
                    [self loginFailed];

                    // Hide activity indicator
                    [HUD hideUIBlockingIndicator];
                }

            } else {

                // Login error
                if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Ingen nätverksuppkoppling hittades." :@"Ett fel har inträffat!"];
                [self loginFailed];

                // Hide activity indicator
                [HUD hideUIBlockingIndicator];
            }
        }
    }
    @catch (NSException * e) {

        // Login error
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Inloggningen misslyckades." :@"Ett fel har inträffat!"];
        [self loginFailed];

        // Hide activity indicator
        [HUD hideUIBlockingIndicator];
    }
}

【问题讨论】:

    标签: objective-c json login connection activity-indicator


    【解决方案1】:

    我认为问题是由于使用了sendSynchronousRequest:returningResponse:error:

    此方法将阻塞主/UI 线程,因此 HUD 永远不会真正有机会显示,直到该方法返回,此时代码继续并且 HUD 被隐藏。

    我认为您应该考虑使用异步请求。 并实现NSURLConnection 委托方法。

    编辑:添加了代码示例。

    假设您的目标是 iOS 5 及更高版本,您可以使用以下代码 sn-p,它利用带有 sendAsynchronousRequest:queue:completionHandler: 和 GCD 的块。

    NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:backgroundQueue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    
                               // NOTE: This block is called on the background queue.
    
                               // Use GCD to get back onto the main thread
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   // This block will process the response and data on the main thread
                               });
    
                           }];
    

    将现有代码移植到使用这种机制的工作量非常小。如果您不知道块是如何工作的,您应该阅读the documentation,因为它们是一种非常强大的语言功能,并且正在越来越多的 Apple 和第三方框架中使用。

    我还建议您暂时远离第三方网络库,直到您了解可能导致此类问题的细微差别。

    【讨论】:

    • 无论如何你能帮我实现你对@SteveWilford上面代码的建议吗?
    • @Oskar 我已经编辑了我的答案以包含一个小代码 sn-p 这应该会让你走上正确的轨道:)
    • 我会在您提供的帮助下尝试解决这个问题。但为什么该方法会阻塞主/UI 线程,所以在方法返回之前,HUD 不会显示?
    • 它会阻塞以正常运行,如果它立即返回,那么您将无法访问响应。有关此方法的具体细节,请参阅docs。我还建议阅读 threading 以及为什么它很重要。
    • This link 也很好地描述了同步与异步请求,尽管使用的是较旧的基于委托的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多