【问题标题】:Display UIAlertView if my JSON does not load?如果我的 JSON 未加载,是否显示 UIAlertView?
【发布时间】:2012-10-24 12:57:04
【问题描述】:

这是我的问题。如果我的应用无法加载远程 JSON 文件,我该如何显示错误?我在我的电脑上关闭了我的 wifi 并在模拟器中运行了该应用程序。如果有连接,它 NSLogs 应该显示的消息。我怎样才能解决这个问题?谢谢。

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *jsonStr = @"http://xxx.com/server.php?json=1";
    NSURL *jsonURL = [NSURL URLWithString:jsonStr];
   // NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
   // NSError *jsonError = nil;
    NSURLRequest *jsonLoaded = [NSURLRequest requestWithURL:jsonURL];

    if(!jsonLoaded) {

        UIAlertView *alertView = [[UIAlertView alloc] init];
        alertView.title = @"Error!";
        alertView.message = @"A server with the specified hostname could not be found.\n\nPlease check your internet connection.";
        [alertView addButtonWithTitle:@"Ok"];
        [alertView show];
        [alertView release];
        NSLog(@"No connection, JSON not loaded...");

    }
    else {
        NSLog(@"JSON loaded and ready to process...");
    }
}

【问题讨论】:

    标签: ios error-handling uialertview


    【解决方案1】:

    您的代码只是创建请求。它实际上并没有获取数据。您需要使用NSURLConnection 来获取数据。

    有多种方法可以获取数据。此示例适用于 iOS 5.0 或更高版本:

    NSOperationQueue *q = [[[NSOperationQueue alloc] init] autorelease];
    NSURLRequest *jsonRequest = [NSURLRequest requestWithURL:jsonURL];
    [NSURLConnection sendAsynchronousRequest:jsonRequest
                                       queue:q
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               // data was received
                               if (data)
                               {
                                   NSLog(@"JSON loaded and ready to process...");
                                   // ... process the data
                               }
                               // No data received
                               else
                               {
                                   NSLog(@"No connection, JSON not loaded...");
                                   // ... display your alert view
                               }
                           }];
    

    【讨论】:

    • 谢谢,我现在就试试这个。我该在哪里插入此代码?在 NSUrl 下?
    • 这仍然不起作用。我的 json 位于外部 URL。我的 wifi 我们关闭了,它仍然说 json 已加载,但它不可能加载。
    • 你的代码现在可以工作了,但它只是 NSLogs... 它没有显示 alertview。
    【解决方案2】:

    您实际上还没有请求任何东西。阅读here 了解如何提出请求。

    基本上,你要做的是实现NSURLConnectionDelegate协议并重写connection:didFailWithError:函数来监听失败事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2012-07-27
      • 2012-03-20
      • 2016-04-08
      相关资源
      最近更新 更多