2013-08-19 146 views
0

當我運行我的應用程序,如果沒有互聯網連接它直接終止我的應用程序並顯示此消息。NSJSONSerialization終止應用程序,如果沒有互聯網連接

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil

- (void)viewDidLoad 
{ 
response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://example.com/jsonTest.php"]]; 

NSError *parseError = nil; 

jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&parseError]; 

jsonArray1 = [[NSMutableArray alloc] init]; 

for(int i=0;i<[jsonArray count];i++) 
{ 
    ... 
    .. 
    . 
} 

} 

我曾嘗試下面這段代碼顯示的警報視圖,但沒有顯示,我是不是做錯了什麼?

-(void)uploadRequestFailed:(NSJSONSerialization *)request 
{ 
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"No internet connection" message:@"Please check the internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [alert show]; 
} 
+1

我認爲你的應用程序終止,因爲你沒有網絡連接時傳遞'nil'數據到'NSJSONSerialization'。 – Exploring

+0

當沒有網絡時,您的回覆爲零。 – SRI

回答

1

把狀態這樣

if(response!=nil) { 

    jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&parseError]; 

    jsonArray1 = [[NSMutableArray alloc] init]; 

    for(int i=0;i<[jsonArray count];i++) 
    { 
     ... 
     .. 
     . 
    } 
} 
+1

仍然應該考慮一個'if'語句來測試'jsonArray'爲零,因爲響應可能無法被解析。 –

+0

它的效果很好:) –

+0

如果您發現我的答案有幫助,請將其標記爲正確答案 – SRI

2

如果您沒有互聯網連接,您的響應對象將爲零。因此,您的NSJSONSerialization調用將引發異常,因爲第一個參數爲零。

假設您可以使用它實例化一個JSON,您應該檢查響應是否爲零。

+0

它的工作原理,我忘記如果聲明。謝謝 –

1

它,因爲你正在做webcall和服務器

response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://example.com/jsonTest.php"]]; 

獲取數據,但沒有有效的連接,所以你什麼也得不到響應變量。當你將這個迴應傳給jsonarray的時候無法解析它。所以錯誤發生。我會建議在做網絡檢查之前檢查互聯網連接。如果存在活動連接,則只有您可以撥打服務器電話。您可以檢查互聯網連接這樣的:

- (BOOL) connectedToNetwork 
{ 
    // Create zero addy 
    struct sockaddr_in zeroAddress; 
    bzero(&zeroAddress, sizeof(zeroAddress)); 
    zeroAddress.sin_len = sizeof(zeroAddress); 
    zeroAddress.sin_family = AF_INET; 

    // Recover reachability flags 
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); 
    SCNetworkReachabilityFlags flags; 

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); 
    CFRelease(defaultRouteReachability); 

    if (!didRetrieveFlags) 
    { 
     return NO; 
    } 

    BOOL isReachable = flags & kSCNetworkFlagsReachable; 
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; 
    return (isReachable && !needsConnection) ? YES : NO; 
} 

此代碼的工作添加庫:

SystemConfiguration.framework 

並導入這類

#import <SystemConfiguration/SystemConfiguration.h> 

希望它幫助!

+0

這也是一個很不同的解決方案。 –

相關問題