0

Error:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

This is my expected json response :

{
"success": true
"mobile": 90xxxxxxxx
"message": "OTP is generated and sent successfully"
}

This is my code :

NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
    [request setURL:url];
        [request setHTTPMethod:@"POST"];
        NSString *conLength=[NSString stringWithFormat:@"%lu",(unsigned long)data.length];
        [request setValue:conLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:data];

     NSURLSession *session = [NSURLSession sharedSession];
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                    completionHandler:
                                          ^(NSData *data, NSURLResponse *response, NSError *connectionError) {
                                              // ...
                                              NSLog(@"coming inside session side");
                                              dispatch_async(dispatch_get_main_queue(),^{

                                                  if([data length]>0 && connectionError==nil)
                                                  {
                                                      NSError *error;


                                                      NSMutableDictionary *jsonResponse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

                                                      if(error)
                                                      {
                                                          [Utitlity alertFunction:@"Warning" message:[error localizedDescription]];
                                                          NSLog(@"%@",error);
                                                      }
                                                      else
                                                      {
                                                          [self requestComplete:jsonResponse];
                                                      }
                                                  }
                                                  else if ([data length] == 0 && connectionError == nil)
                                                  {
                                                      [Utitlity alertFunction:@"Warning" message:@"Empty Server Response"];
                                                  }
                                                  else if (connectionError != nil)
                                                  {
                                                      [Utitlity alertFunction:@"Warning" message:@"Problem in connecting to server"];
                                                  }
                                              });
                                          }];

            [task resume];

converting string into nsdata for post method:

-(void)loginotpmobilnumber:(NSString *)mobile
{

    NSString *url=[NSString stringWithFormat:@"mobile=%@",mobile];
    NSData *dataFetch=[url dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSURL *urla=[NSURL URLWithString:[NSString stringWithFormat:@"%@",loginotp]];
    [self requestFunction:urla :dataFetch :YES];
}

My other post method and get methods are all working except this whats wrong ?

Rumin
  • 3,787
  • 3
  • 27
  • 30
Kishore Kumar
  • 4,265
  • 3
  • 26
  • 47
  • your json is wrong. I formatted it with an online editor and it gives error. After ever key value pair there is a , and "90xxxxxx" should be a string. you can check here http://www.jsoneditoronline.org – Muhammad Zohaib Ehsan Feb 08 '16 at 06:53
  • so @MuhammadZohaibEhsan json response is wrong correct? – Kishore Kumar Feb 08 '16 at 06:54
  • yes I guess. i tried to format it with online editor and it give error parsing it. Perhaps can we provide custom style to parse json, i guess not. try yourself in the online editor link . You can analyse it. – Muhammad Zohaib Ehsan Feb 08 '16 at 06:57
  • @KishoreKumar did you try to log the string that's being received? You could convert the data being received to the `NSString` and `NSLog` it. – Fahri Azimov Feb 08 '16 at 07:03
  • You just need to tel your backend team for correct the json formats that issue not related to parsing method that issue from backed. Some whare in response some unwanted character type in code so that error happen. – Nitin Gohel Feb 08 '16 at 07:04
  • Yes, the "expected" JSON is not valid. You're missing some commas and if the phone number might contain spaces or punctuation or anything but digits, it must be quoted. But your error message suggests a more fundamental problem: I'd suggest you examine the contents of the response body and see what it looks like. Look at `[[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding]` and see what it says. I bet it's not JSON at all. Or watch the response with something like [Charles](http://charlesproxy.com) and see what the body of the response actually contains. – Rob Feb 08 '16 at 07:22
  • By the way, you don't need to set the `Content-Length` header. That's done for you. – Rob Feb 08 '16 at 07:29
  • 404 Page Not Found404 Page Not Found

    The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

    Visit the Home Page

    @Rob i printed in nsstring its giving like this

    – Kishore Kumar Feb 08 '16 at 07:30
  • Yup, as I expected, the problem is not related t the `JSON`. Check your url string, where you are sending the request, make sure the host and all the parameters being sent are correct. – Fahri Azimov Feb 08 '16 at 07:32
  • but url is correct bro @FahriAzimov i copied url and pasted advance rest client api its asking some post data .:( – Kishore Kumar Feb 08 '16 at 07:41
  • {"success":false,"error":"Mobile Number is Required!"} – Kishore Kumar Feb 08 '16 at 07:42
  • I'd suggest examining your URL variable that you're using when building the request, because it's apparently not correct. Maybe you there is an error in building the full URL. But the server response is quite clear, that the supplied URL was not found on the server. – Rob Feb 08 '16 at 08:06

0 Answers0