Search code examples
objective-cnsstringnslognsstreamnsmutablestring

NSLog show strange character instead of the JSON


I have this code below that handles the response send by my server with sockets:

uint8_t buffer[4096];
        int len;
        NSMutableString *total = [[NSMutableString alloc] init];
        while ([inputStream hasBytesAvailable]) {
            len = (int)[inputStream read:buffer maxLength:sizeof(buffer)];
            if (len > 0) {

                NSLog(@"Buffer: %s",buffer);
                [total appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]];
                NSLog(@"Receive: %@, len: %d",total,len);
                NSLog(@"len: %d, receive: %@",len,total);

}

}

My server send a text file like this:

[{"name_user":"stack overflow","user_key":"XXXXXXX","type":21}]

The problem with this code is, if I send that JSON, the console log shows the length of that JSON. But If I send this JSON below:

[[{"name_user":"stack overflow","user_key":"XXXXXXX","type":21}],[{"name_user":"lacrifilm","user_key":"XXXXXXX","type":21}]]

That represents two values in JSON the console log shows:

Buffer: ~
Receive: ~
len: 184, receive: ~

I believe the problem is not in my server, because if it was I would be getting: Receive: ~, len: 184, instead of Receive: ~ without len: 184 as we saw in the second call of NSLog in my command above.

How can I solve this problem?


Solution

  • You are building up your string incorrectly. You are reading a series of bytes, not pieces of a string. So build up an NSMutableData, and then create an NSString once you have all of the data. More like this:

    uint8_t buffer[4096];
    NSMutableData *data = [[NSMutableData alloc] init];
    while ([inputStream hasBytesAvailable]) {
        NSInteger len = [inputStream read:buffer maxLength:sizeof(buffer)];
        if (len > 0) {
            //NSLog(@"Buffer: %s",buffer); // can't do this - buffer isn't a null-terminated C-string
            [data appendBytes:buffer length:len];
            NSLog(@"Receive: %@, len: %d", data, (int)len);
        }
    }
    
    NSString *total = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Total: %@", total);