2016-08-04 66 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> 

下标签。一切都会好起来的。

相关问题