Search code examples
iosobjective-cserverafnetworking-2

error while getting data from server using Afnetworking


i wanted to get data from server encoded in json to display it, so i use afnetworking library but i get error here is my code

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

here is the error

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.


Solution

  • It looks like you are trying to parse a JSON response with AFJSONResponseSerializer, but the webserver sends text/html as content type. JSON responses are generally served with the Content-Type: application/json header.

    Also, if the response was successfully parsed as JSON, the responseObject given as the second parameter of your completion block would already be a valid NSArray containing your data. So there wouldn't need to create it again using NSJSONSerialization.