dan*_*dam 4 iphone json objective-c ios afnetworking
我正在尝试从服务JSON的Web服务获取一些数据.但我不知道我的代码出了什么问题.它看起来很简单但我无法获得任何数据.
这个代码:
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
DumpDic = (NSDictionary*)[JSON valueForKeyPath:@"description"] ;
}
failure:nil
];
[operation start];
AboutTXT = [DumpDic objectForKey:@"description"];
Run Code Online (Sandbox Code Playgroud)
这是JSON URL.
编辑
来自URL的JSON:
{
"clazz":"AboutList",
"description":{
"clazz":"DescriptionContent",
"description":"ASTRO Holdings Sdn. Bhd. (AHSB) Group operates through two holding companies – ASTRO Overseas Limited (AOL) which owns the portfolio of regional investments and ASTRO Malaysia Holdings Sdn Bhd (AMH / ASTRO) for the Malaysian business, which was privatized in 2010 and is currently owned by Usaha Tegas Sdn Bhd/its affiliates, and Khazanah Nasional Berhad."
},
"id":{
"inc":-1096690569,
"machine":1178249826,
"new":false,
"time":1339660115000,
"timeSecond":1339660115
},
"refKey":"AboutList"
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*itz 13
是否成功连接到服务器,是否正在调用成功块?
填写故障块和NSLog失败块返回的NSError:
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"%@", [error userInfo]);
}
Run Code Online (Sandbox Code Playgroud)
我还有一个提示,我建议使用AFNetwork的AFHTTPClient构建NSURLRequest,它可以帮助处理各种事情,并且通常会使事情变得更简单.您设置基本URL,然后为其添加一个附加到该基础的路径.像这样的东西:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:address];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST"
path:@"events"
parameters:dict];
Run Code Online (Sandbox Code Playgroud)
也可以建议您只使用objectForKey而不是使用valueForKeyPath:
[JSON objectForKey:@"description"];
Run Code Online (Sandbox Code Playgroud)
此外,您不应该访问DumpDic:
[operation start];
AboutTXT = [DumpDic objectForKey:@"description"];
Run Code Online (Sandbox Code Playgroud)
这是一个异步调用,因此一旦操作开始,DumpDic很可能在从服务器分配数据之前被访问.所以你正在访问一个可能还不存在的密钥.
这应该在成功或失败块中完成.一旦连接完成并且数据准备好被使用,就会调用这些块.
所以看起来应该更像这样:
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
DumpDic = [JSON objectFor:@"description"];
AboutTXT = [DumpDic objectForKey:@"description"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"%@", [error userInfo]);
}];
[operation start];
Run Code Online (Sandbox Code Playgroud)