Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The data couldn’t be read because it isn’t in the correct format

Ok, I am now starting with iOS development and currently playing with NSData using Obj-C. Recently I'm using the URLSession:dataTask:didReceiveData method to get NSData using HTTP POST request. The server will be responding a JSON object containing a JSON array.

Something interesting is that when the response data is too large the NSLog part will print out: "The data couldn't be read because it isn't in the correct format". Below is the function:

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSError *error;
    // get data from NSData into NSDict
    NSDictionary *searchData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSArray *test = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSMutableDictionary *mdict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"what: %@", mdict);
    NSLog(@"received data length: %@", [NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);
    if (error) {
        NSLog(@"json error: %@", [error localizedDescription]);
    }
}

Just wondering if anyone knows the potential reason causing this problem ??

[Update]

Well, an alternative to solve this problem might be using NSString for data storage. But would have to parse it by myself. I would prefer using NSDictionary though.

like image 762
4Gred__ Avatar asked Dec 08 '22 22:12

4Gred__


1 Answers

Beginner problem: didReceiveData is called when some of the data has arrived, before the data is complete. Read the documentation of didReceiveData, which explains what you need to do. You are trying to parse incomplete data. That won't work.

And when you are handling JSON data, you should never involve any NSString objects, except possibly to log data.

like image 63
gnasher729 Avatar answered Dec 11 '22 12:12

gnasher729