11
votes

Hi I am new in iOS and I am trying to get response from web-service using JSON but following error occurs. Please help me to solve it.

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7fd30bee0f70 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x7fd30bede7b0 "Request failed: internal server error (500)"}

-(void)loadFeedWithOffset:(NSInteger)Offset Limit:(NSInteger)Limit
{
     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//      [manager.requestSerializer setValue:@"application/json;                 text/html" forHTTPHeaderField:@"Accept"];
//      [manager.requestSerializer setValue:@"application/json;     text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"user_id"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Offset] forKey:@"offset"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Limit] forKey:@"limit"];
    [params setValue:[NSString stringWithFormat:@"%d",[AppDelegate sharedAppDelegate].intPostType] forKey:@"post_type"];

    [manager POST:[NSString stringWithFormat:@"%@webservices/post/load", API_URL] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
 {

     NSLog(@"JSON: %@", responseObject);
     if ([[responseObject objectForKey:@"status"] isEqualToString:@"fail"])
     {
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[responseObject objectForKey:@"message"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
         [alert show];
         alert = nil;
     }
     else
     {
         if ([[responseObject objectForKey:@"feed"] count] > 0)
         {
             isOver = FALSE;
             [arrFeed addObjectsFromArray:[responseObject objectForKey:@"feed"]];
             searchedDataArray = [NSMutableArray  arrayWithArray:arrFeed];
             //searchedDataArray=arrFeed;
             [tblMenuDetail reloadData];
         }
         else
         {
             isOver = TRUE;
         }
         [self performSelector:@selector(doneLoadingTableViewData) withObject:self afterDelay:1.0];
     }
     [[AppDelegate sharedAppDelegate] hideProgress];
 } failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     [[AppDelegate sharedAppDelegate] hideProgress];
     NSLog(@"Error: %@", error);
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
     [alert show];
     alert = nil;
 }];
}
9
what does the json look likeFonix
right know i am not getting any response from the server so i don't know response is in which formatBirendra
I change the above code but still error coming and error is serialization.response Code=-1011 "Request failed: internal server error (500)"Birendra
The error could be on server side. Try to use postman or any other application to simulate your post request using your params as parameter.seto nugroho
Please check my code posted below and let me know if any concern. :)Sandip Patel - SM

9 Answers

11
votes

This is usually a back-end related issue, the json is not well formated and there is nothing you can do about it on client side ....

Although sometimes this occurs when wrong parameters are sent to back-end, so you could check if all parameters are correct (both type and value)

2
votes

Try setting the content-type as json

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

2
votes

I was having same problem with AFNetworking, this is because your response coming from server is holding string and not JSON Dictionary or Array. So i fixed it by adding below line of code

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

Hope it may work for you too. All the best:)

1
votes

I am having the same issue, I am getting an encrypted response from server, what I did solves the issue.

manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Give it a try.

1
votes

This is not JSONSerialization or swift error.

The problem comes from response parsing. You are trying to de-serialize a JSON response (which MUST be contained in either a Array or Dictionary) however your response is none of the above (Most likely a simple string).

try this code to print out our server data to easily identifying to error and resolve this.

URLSession.shared.dataTask(with: url) { (data, response, error) in

    if let jsonData = data {
        do {
            let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: AnyObject]
        }
        catch let err{
            print("\n\n===========Error===========")
            print("Error Code: \(error!._code)")
            print("Error Messsage: \(error!.localizedDescription)")
            if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
                print("Print Server data:- " + str)
            }
            debugPrint(error)
            print("===========================\n\n")

            debugPrint(err)
        }
    }
    else {
        debugPrint(error as Any)
    }

}.resume()
0
votes

Here is solution, Use below code and it will work:

//Note: web-service using JSON

NSString *strAPIURL = [NSString stringWithFormat:@"%@webservices/post/load", API_URL];

NSDictionary* dictHeader = @{@"content-type": @"application/json"};  //You can add here more header field if require, like "Authorization"

NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"user_id"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Offset] forKey:@"offset"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Limit] forKey:@"limit"];
    [params setValue:[NSString stringWithFormat:@"%d",[AppDelegate sharedAppDelegate].intPostType] forKey:@"post_type"];



    NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strAPIURL]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:30.0];
    [request setHTTPMethod:@“POST”];
    [request setAllHTTPHeaderFields:dictHeader];
    [request setHTTPBody:postData];

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

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);

       //Success code…

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

    //Failure code…

    }];

    [operation start];

    return operation;
0
votes

I also have this issue, but if you wants to make sure this issue is from server side or back end then try hitting web service using postman and check response in either Raw section or in Preview section. These sections shows exact response which we get using web service. Preview sections shows exact information / issue like line no, function name etc.

0
votes

In my case i set .jsonobject options: as array, thats why i'm getting this error.

let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]

This is my code here i send [ ] for options, later i changed from array to .allowFragments

My solution is..

let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
0
votes

This error also can occur if your url isn't faulty enough to cause the api to return an error or bad response, but having faults which contain something odd the api didn't like. For instance:

example 1: appendingPathExtension(".json") could add an extra unwanted ".." period, bc this method ALREADY adds the 'dot for you.

example 2: url was constructed by adding the query as url/string via a method other than using URLQueryItem Class and .queryItems method. In Swift 5 this can cause a "?" in your request to be a different symbol, or have the api miss your apiKey or queryItem alltogether. So anywhere you see "?" in your example request url, make sure to use queryItems (see documentation).

Here's an example of successful URL construction including a single query item which is the api_key at the very end...

    let heirarchyURL = baseURL.appendingPathComponent("league").appendingPathComponent("hierarchy").appendingPathExtension("json")

    var components = URLComponents(url: heirarchyURL, resolvingAgainstBaseURL: true)

    let keyQuery = URLQueryItem(name: "api_key", value: apiKey)

    components?.queryItems = [keyQuery]

    guard let url = components?.url else {
        NSLog("components of url failed to load properly")
        completion()
        return
    }

    print("fetch URL: \n\(url)\n")

    let request = URLRequest(url: url)

    URLSession.shared.dataTask(with: request) { (data, _, error) -> Void in