2
votes

I am unable to get data using this approach, however its working when using other url and i have also tested in postman where i am getting response.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

// if you want to sent parameters you can use above code

manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager GET:@"http://192.168.1.156:81/a.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"responseObject %@",responseObject);

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

}];

Error:

"Request failed: unacceptable content-type: text/html" UserInfo=0x8a6b000 {NSErrorFailingURLKey=http://192.168.1.156:81/a.php, AFNetworkingOperationFailingURLResponseErrorKey= { URL: http://192.168.1.156:81/a.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Type" = "text/html";
    Date = "Tue, 20 May 2014 14:49:20 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = "Apache/2.4.4 (Win64) PHP/5.4.12";
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "PHP/5.4.12";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}

NSArray Conversion Error:

Parsing JSON failed: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid escape sequence around character 4677.) UserInfo=0xa82c130 {NSDebugDescription=Invalid escape sequence around character 4677.}

Parse error on line 258:
...     "story_title": "today\'s story",  
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
3
Have you examined the NSError object in the failure block? What does it say?Rob
@Rob - I have updated my question with answeruser3635892
Unrelated to your question, but, BTW, it's a little curious to specify a AFJSONRequestSerializer for a GET request. GET requests don't have a body, but rather encode their parameters in the URL. And, besides, you don't have any parameters.Rob

3 Answers

4
votes

Your error message is telling you that AFNetworking was expecting a JSON response (i.e., the Content-Type of the header of the response should be application/json and the body of the response should be the actual JSON).

One of number of possibilities here:

  1. Your service is returning a JSON body, but neglected to specify the Content-Type header. In your PHP code, before sending any data, specify the Content-Type header:

    header("Content-Type: application/json");
    

    If you cannot fix the PHP (which is the preferred solution), you can alternatively tell AFNetworking to accept also text/html as a Content-Type. I haven't tested this, but something like the following should add text/html to the set of acceptableContentTypes of the default AFJSONResponseSerializer:

    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
  2. Your web service is not designed to return JSON. In that case, you should configure the manager to accept non-JSON responses, e.g.:

    mananger.responseSerializer = [AFHTTPResponseSerializer serializer];
    
  3. Your web service is designed to properly return JSON responses, but it encountered some programmatic error that prevented the JSON from being properly generated. In that case, it can be useful to temporarily change the manager to accept non-JSON responses (like point 2, above), and then examine the response (assuming, of course, you've configured your php.ini to report errors):

    NSLog(@"responseObject = %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding);
    

    If you're seeing your JSON, you could convert that to an array using NSJSONSerialization:

    NSError *error;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
    if (!array) {
        NSLog(@"Parsing JSON failed: %@", error);
    }
    

    Obviously, you can then save this local NSArray object into whatever class property or instance variable you want.


You've updated your question with the JSON parsing error. This is a result of the \ character in the JSON. That's not valid. (Paste your JSON in http://jsonlint.com and it will confirm this.) Your PHP is not generating the JSON correctly. Remove that \ before the '. You should use this backslash escape only when including double quotes in your JSON.

Frankly, it looks like you created this JSON manually. It's much better to use PHP function json_encode which does all of the appropriate escaping for you, avoiding these sorts of JSON errors altogether.

0
votes

-(void)load_home_page_data_withIndex:(NSString *)startindex andTotalRecord:(NSString *)count {

NSDictionary *favParameter;
NSString *URL1;
[MBProgressHUD showHUDAddedTo:[[[UIApplication sharedApplication] delegate] window] animated:YES];

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];

NSString *uId=[defaults valueForKey:@"UserID"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

URL1=[BASE_URL stringByAppendingString:@"home"];
favParameter=@{
               @"user_id":uId,//[defaults valueForKey:@"UserID"
             //  @"no":startindex,
             //  @"total_record":count,
               };

AFHTTPRequestOperation *op = [manager POST:URL1 parameters:favParameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
}
                                   success:^(AFHTTPRequestOperation *operation, id responseObject)

                              {
                                  __weak Home *weakSelf = self;
                                  [weakSelf.tblObj.pullToRefreshView stopAnimating];
                                  [weakSelf.tblObj.infiniteScrollingView stopAnimating];

                                  [MBProgressHUD hideHUDForView:[[[UIApplication sharedApplication] delegate] window] animated:YES];

                                  NSError *jsonParsingError = nil;
                                  NSMutableDictionary *responseDict = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];


                                  [album_id removeAllObjects];
                                  [photo_id removeAllObjects];
                                  [photo_name removeAllObjects];
                                  [likes removeAllObjects];
                                  [user_id removeAllObjects];
                                  [is_like removeAllObjects];
                                  [Owner_id removeAllObjects];
                                  [imagesarr removeAllObjects];
                                  [user_name removeAllObjects];
                                  [arrPhotoDetail removeAllObjects];
                                  [share_name removeAllObjects];
                                  [date_time removeAllObjects];

                                  [_tblObj setContentOffset:CGPointMake(0, 0)];

                                  int count_notification = [[responseDict valueForKey:@"count_notification"] intValue];
                                  int count_friend_notification = [[responseDict valueForKey:@"count_friend_notification"] intValue];

                                  if (count_notification>0)
                                  {
                                      [_lblNotification_count setText:[NSString stringWithFormat:@"%@  ",[responseDict valueForKey:@"count_notification"]]];
                                      [_lblNotification_count setHidden:NO];
                                  }
                                  else
                                  {
                                      [_lblNotification_count setHidden:YES];
                                  }

                                  if (count_friend_notification>0)
                                  {
                                      [_lblFriendReq_count setText:[NSString stringWithFormat:@"%@  ",[responseDict valueForKey:@"count_friend_notification"]]];
                                      [_lblFriendReq_count setHidden:NO];
                                  }
                                  else
                                  {
                                      [_lblFriendReq_count setHidden:YES];
                                  }

                                  NSString *s1=[NSString stringWithFormat:@"%@",[responseDict valueForKey:@"success"]];
                                  //NSString *s2=[NSString stringWithFormat:@"%@",[responseDict valueForKey:@"msg"]];

                                  if ([s1 isEqualToString:@"1"])
                                  {
                                      [_imgNoData setHidden:YES];

                                      NSMutableArray *arrResult=[responseDict objectForKey:@"result"];

                                      for (int i=0; i<[arrResult count]; i++)
                                      {
                                          NSDictionary *ResultDisc=[arrResult objectAtIndex:i];

                                          [album_id addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"album_id"]]];
                                          [user_name addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"user_name"]]];
                                          [share_name addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"title"]]];
                                          [photo_name addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"user_image"]]];
                                          [likes addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"total_likes"]]];
                                          [is_like addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"is_like"]]];
                                          [arrPhotoDetail addObject:[ResultDisc valueForKey:@"images"]];
                                          [date_time addObject:[NSString stringWithFormat:@"%@",[ResultDisc valueForKey:@"datetime1"]]];

                                          //images
                                          NSArray *arrAns = [ResultDisc valueForKey:@"images"];
                                          NSMutableArray *arr = [[NSMutableArray alloc]init];
                                          //imagesarr
                                          for (int i=0; i<arrAns.count; i++)
                                          {
                                              [arr addObject:[[arrAns objectAtIndex:i] valueForKey:@"photo_title"]];
                                              [Owner_id addObject:[NSString stringWithFormat:@"%@",[arrAns valueForKey:@"owner_id"]]];
                                              [photo_id addObject:[NSString stringWithFormat:@"%@",[arrAns valueForKey:@"photo_id"]]];
                                          }
                                          [imagesarr addObject:arr];
                                          if([ResultDisc objectForKey:@"reviews"] != nil && [[ResultDisc objectForKey:@"reviews"] count] > 0) {
                                              [review addObject:[[ResultDisc objectForKey:@"reviews"] objectAtIndex:0]];
                                          }
                                          else {
                                              [review addObject:@""];
                                          }
                                      }
                                  }
                                  else
                                  {
                                      [_imgNoData setHidden:NO];
                                  }
                                  [_tblObj reloadData];

                              }
                                   failure:^(AFHTTPRequestOperation *operation, NSError *error)
                              {
                                  __weak Home *weakSelf = self;
                                  [weakSelf.tblObj.pullToRefreshView stopAnimating];
                                  [weakSelf.tblObj.infiniteScrollingView stopAnimating];

                                  [MBProgressHUD hideHUDForView:[[[UIApplication sharedApplication] delegate] window] animated:YES];
                                  [Utilities displayAlertWithTitle:@"Network Error" andMessage:@"" forView:self];
                              }];
[op start];

}

0
votes

Try lazy loading:

[cell.Profile_btn setBackgroundImageForState:UIControlStateNormal 
                  withURL:[NSURL URLWithString: [
                      NSString stringWithFormat:@"http://downloadwhatsbest.com/assets/front/users/thumb/%@",
                          [photo_name objectAtIndex:indexPath.row]
                      ]
                  ]
                  placeholderImage:[UIImage imageNamed:@"USER_INVITE"]];

I've formatted it for better reading. Remove whitespaces.