使用Afnetworking从服务器获取数据时出错

时间:2015-01-29 19:14:43

标签: ios objective-c server afnetworking-2

我想从json中编码的服务器获取数据来显示它,所以我使用afnetworking库但我得到的错误是我的代码

  NSURL * url =[NSURL URLWithString:@"http://software-sultan.com/alaa/image_test.php"];

NSURLRequest * request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // 3
    array = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];



} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // 4
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                        message:[error localizedDescription]
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
    [alertView show];
    NSLog(@"%@",error);
}];

// 5
[operation start];

这是错误

Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x7f920964bff0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f920965cc20> { URL: http://software-sultan.com/alaa/image_test.php } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 126781;
"Content-Type" = "text/html";
Date = "Thu, 29 Jan 2015 19:00:55 GMT";
"Keep-Alive" = "timeout=30";
Server = "Apache/2";
"X-Powered-By" = "PHP/5.3.13";

}},NSErrorFailingURLKey = http://software-sultan

1 个答案:

答案 0 :(得分:0)

您似乎尝试使用AFJSONResponseSerializer解析JSON响应,但网络服务器将text/html作为内容类型发送。 JSON响应通常与Content-Type: application/json标头一起提供。

此外,如果响应已成功解析为JSON,则作为完成块的第二个参数的responseObject已经是包含您的数据的有效NSArray。因此,无需使用NSJSONSerialization再次创建它。