我目前正在尝试像这样创建一个JSON数组:
NSURL *url = [NSURL URLWithString:currentJSON];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
if (jsonData) {
result = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
}
哪个工作正常。如果互联网连接不好,我想让它超时。
所以我接着在AFNetworking上编写了这样的代码:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:currentJSON parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
result = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingMutableContainers
error:&error];
[[NSUserDefaults standardUserDefaults] setObject:result forKey:@"All"];
[[NSUserDefaults standardUserDefaults] synchronize];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
result = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"All"];
}
但是这个方法总是运行到failure
怎么样?我做错了什么?
答案 0 :(得分:2)
检查服务器是否使用正确的内容类型' application / json'发送JSON。 AFNetowrking开箱即用,如果收到其他内容(例如' text / html'),将调用失败块。
此外,AFNetworking将JSON用于对象解析开箱即用。 ' id responseObject'已经是' [NSJSONSerialization JSONObjectWithData]'的结果。
如果您无法更改服务器发送的内容类型,则可以使用以下代码段将该内容类型添加到接受的类型
NSMutableSet *accepted = [NSMutableSet set];
[accepted addObject:@"text/html"];
[accepted addObject:@"application/json"];
manager.responseSerializer.acceptableContentTypes = accepted;
答案 1 :(得分:0)
试试这个:
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
result = (NSDictionary *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];