2016-08-04 52 views
0

這裏是代碼我想要存儲JSON數據,並使用它時,需要IOS

NSString *url = @"http://somesite.com/"; 
    NSURL *stringURL = [NSURL URLWithString:url]; 
    NSLog(@"url-------- %@",stringURL); 
    NSData *urlData = [NSData dataWithContentsOfURL:stringURL]; 
    NSLog(@"data---------%@",urlData); 

    if (urlData) 
    { 
     // JSON successfully downloaded 
     NSLog(@"yes "); 
    } 
    else 
    { 
     NSLog(@"not exist"); 
    } 

當我嘗試打印的NSData我給我空,並且控制轉到別的塊。請糾正我..我想存儲JSON數據,並在需要它的地方使用它

+0

你解決了嗎? – Jassi

回答

0

你可以嘗試NSURL線以下後,更改代碼:

NSError* error = nil; 
NSData* data = [NSData dataWithContentsOfURL:stringURL options:NSDataReadingUncached error:&error]; 
if (error) { 
    NSLog(@"%@", [error localizedDescription]); 
} else { 
    if (urlData) 
    { 
     // JSON successfully downloaded 
     NSLog(@"yes "); 
    } 
    else 
    { 
     NSLog(@"not exist"); 
    } 
} 
0

如果原始數據格式無效,NSData將返回nil。 你可以使用--initWithContentsOfURL:options:error:獲取錯誤信息。

2

你的代碼是正確的。我認爲,您的App Transport安全性出現錯誤。 當我運行你的代碼時,我發現一個錯誤 -

「App Transport Security由於不安全而阻止了明文HTTP(http://)資源加載臨時異常可以通過你的應用的Info.plist文件。」

爲了解決這個問題,去你的項目的Info.plist文件,右擊它並選擇這樣的源代碼選項 -

enter image description here

然後,只需粘貼

<key>NSAppTransportSecurity</key> 
<dict> 
    <key>NSAllowsArbitraryLoads</key> 
    <true/> 
</dict> 

下標籤。一切都會好起來的。

相關問題