我正在使用AFHTTPRequestOperation来获取几个要解析的HTML页面。
我遇到的问题是,例如,如果我使用了错误的端口号,则在连接到服务器时,“失败”错误块不会触发。相反,会触发完成块,但响应字符串为nil。
我只是从ASIHTTP切换到AFNetworking,而使用ASIHTTP会产生错误。
当然应该提供一个错误吗?我该如何捕捉?
NSString *urlString;
urlString = [NSString stringWithFormat:@"%@://%@:%@/",kHttp,_IP,_Port];
NSURL *url = [NSURL URLWithString:urlString];
// Set authorization
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setAuthorizationHeaderWithUsername:_User password:_Pass];
NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"Info.htm" parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([self parseInfoLive:operation.responseString])
_count_parsed++;
if (_count_parsed == 2)
[[NSNotificationCenter defaultCenter] postNotificationName:@"downloadsComplete" object:nil];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error during connection: %@",error.description);
[[NSNotificationCenter defaultCenter] postNotificationName:@"errorConnecting" object:nil];
}];
[operation start];
最佳答案
这似乎是AFNetworking中的错误,即使在提出此问题后2.5年也是如此。当响应包含一个特殊字符时会发生这种情况(它可以显示为空格,因为有时甚至文本查看器也无法解析它)。您可以尝试将收到的JSON字符串转换为NSUTF8StringEncoding,然后根据需要将其用作NSData。
NSURL *url = <YOUR REQUEST URL>
NSString *data = [NSString stringWithContentsOfURL:url];
NSData *metOfficeData = [data dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = [NSError new];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:metOfficeData options:kNilOptions error:&error];
关于ios - AFHTTPRequestOperation无响应而不是错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451125/