I've really struggled to figure out why my web service call is riddled with junk data.
I have a UITableViewController that calls the web service and also acts as the NSURLConnectionDelegate.
Here is the delegate method of interest, note the NSLog statements.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"data %@", [[NSString alloc] initWithUTF8String: [data bytes]]);
NSLog(@"before %@", [NSString stringWithUTF8String: self.rawData.bytes]);
[self.rawData appendData:data];
NSLog(@"after %@", [NSString stringWithUTF8String: self.rawData.bytes]);
}
Here is the resulting log after a number of attempts:
2009-07-10 09:04:20.339 SundialInvoice[91493:20b] data {"items": [], "request":
"/inventory/delivered.json"}
2009-07-10 09:04:20.339 SundialInvoice[91493:20b] before
2009-07-10 09:04:20.340 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID
2009-07-10 09:04:23.153 SundialInvoice[91493:20b] data {"items": [], "request": "/inventory/delivered.json"}l 4] [Mes
2009-07-10 09:04:23.154 SundialInvoice[91493:20b] before
2009-07-10 09:04:23.154 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID
2009-07-10 09:04:27.913 SundialInvoice[91493:20b] data (null)
2009-07-10 09:04:27.913 SundialInvoice[91493:20b] before
2009-07-10 09:04:27.914 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID
2009-07-10 09:04:30.486 SundialInvoice[91493:20b] data {"items": [], "request": "/inventory/delivered.json"}ice/1.0 CFN
2009-07-10 09:04:30.487 SundialInvoice[91493:20b] before
2009-07-10 09:04:30.487 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID
Where is the trailing garbage data coming from? I have run the web service with curl several times and the garbage is not coming from it.
To create an NSString
from an NSData
, you should use initWithData:encoding:
, like the following:
NSString *str = [[NSString alloc] initWithData:self.rawData
encoding:NSUTF8StringEncoding];
NSLog(@"Before: %@", str);
[str release];
Treating NSData
bytes as C string might cause some security vulnerabilities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With