5

Im registering device data with the server, to get push notification. Here it goes the code,

[NSURLConnection sendAsynchronousRequest: request
                                           queue: _postQueue
                               completionHandler: ^(NSURLResponse *response, NSData *responseData, NSError *connectionError) {
                                   if (connectionError) {
                                       //
                                   } else {
                                      NSError *error = nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
                                   }
                               }];

Im getting error as

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=0x17057f60 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Can someone please help to fix the issue?

Eran
  • 387,369
  • 54
  • 702
  • 768
rishu1992
  • 1,414
  • 3
  • 14
  • 33

2 Answers2

7

The error message is telling you exactly what's wrong: the response from your server doesn't contain valid JSON. Technically, JSON must start with either an array or an object (dictionary). Whatever your server is returning isn't. You can force the JSON to be consumed regardless by using the NSJSONReadingAllowFragments option.

If after using that option you're still getting errors then your server is probably returning malformed JSON (or no JSON at all). Why don't you take a look at the logs from your server to see exactly what you're sending back?

lxt
  • 31,146
  • 5
  • 78
  • 83
  • Thank you! But when I use NSJSONReadingAllowFragments option Im getting error, Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x1473bee0 {NSDebugDescription=Invalid value around character 0.} – rishu1992 Jan 13 '15 at 06:15
  • So your server is probably not returning JSON, or returning completely invalid JSON. Try printing out your `NSData` as a string instead to see what's getting returned. – lxt Jan 13 '15 at 16:13
  • Thank You! You are correct . Server was checking for extra parameters, apart from those parameters I have sent through app.Some of the parameters were nil. Those nil parameters were causing this issue. – rishu1992 Jan 15 '15 at 07:10
0

I was having same issue look what i have done here

I have change my json parsing method as

let decodedApps = try JSONDecoder().decode(class.self, from: data!)

here class contain all the key which are present in json data key now you can use decodedApps as dictionary .....which contain key value pair may it will helpful

LorenzOliveto
  • 7,796
  • 1
  • 20
  • 47
ankit
  • 1