gpt4 book ai didi

iphone - 使用 AFJSONRequestOperation

转载 作者:可可西里 更新时间:2023-11-01 05:03:29 25 4
gpt4 key购买 nike

我正在尝试从服务于 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"];

这是 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"
}

最佳答案

是否成功连接到服务器,是否调用成功 block ?

填写失败 block 和NSLog失败 block 返回的NSError:

failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"%@", [error userInfo]);
}

我还有一个提示,我建议使用 AFNetwork 的 AFHTTPClient 构建 NSURLRequest,它可以帮助处理各种事情并且通常可以使事情变得更简单。您设置基本 URL,然后为其提供附加到该基本 URL 的路径。像这样:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:address];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST"
path:@"events"
parameters:dict];

另外,我建议您不要使用 valueForKeyPath,而是使用 objectForKey:

[JSON objectForKey:@"description"];

此外,您不应该在那里访问 DumpDic:

[operation start];
AboutTXT = [DumpDic objectForKey:@"description"];

这是一个异步调用,因此一旦操作开始,DumpDic 很可能会在从服务器分配数据之前被访问。所以你正在访问一个可能还不存在的 key 。

这应该在成功或失败 block 中完成。一旦连接完成并且数据可以使用,就会调用这些 block 。

所以它应该看起来更像这样:

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];

关于iphone - 使用 AFJSONRequestOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11034213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com