相关疑难解决方法(0)

NSURLConnection获取JSON文件

我的iOS应用程序正在获取代码(例如101),并通过该代码读取服务器上的JSON文件(例如101.json)并读取其中的数据.一切都运行良好,但如果服务器上没有文件(针对该代码),如何做到这一点(现在它只显示没有数据,如果找不到文件),如果没有互联网连接只是为了从应用程序内的JSON文件中获取数据?这是我的代码:

NSString *baseURLStr = @"http://myserverurl/";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
                                                      URLWithString:[baseURLStr stringByAppendingFormat:@"%d/%d.json", int1, int2]]];
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:nil error:nil];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];  
Run Code Online (Sandbox Code Playgroud)

如果没有互联网连接,我发现如何阅读应用程序内的文件.

if (data == nil){

    NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"FAILED" ofType:@"json"]];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    self.members = json[@"data"];

}
else {

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    self.members = json[@"data"];

}  
Run Code Online (Sandbox Code Playgroud)

json objective-c nsurlconnection

4
推荐指数
1
解决办法
8851
查看次数

标签 统计

json ×1

nsurlconnection ×1

objective-c ×1