2012-11-04 22 views
0

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

这里是我的代码:

- (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..."); 
    } 
} 

回答

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 
          } 
         }]; 
+0

谢谢,我现在就试试这个。我可以插入这段代码吗?根据NSUrl? – 1789040

+0

这仍然不起作用。我的json位于外部URL。我的无线网络关闭了,它仍然说,当它不可能时json被加载。 – 1789040

+0

你的代码现在可以工作,但它只是NSLogs ...它不显示alertview。 – 1789040

0

您还没有实际要求的任何事情。关于如何提出请求,请阅读here

基本上,你想要做的是执行NSURLConnectionDelegate协议并覆盖connection:didFailWithError:函数来侦听失败事件。