Reputation: 16315
I have this code
NSString *tr = [self sendUrl:@"http://google.com/"];
But for some reason 'tr' will remain nil after it is executed. What am I doing wrong?
sendUrl :
- (NSString *)sendUrl:(NSString *) uri {
NSLog(@"Requesting URI 1 ...");
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:uri]];
NSLog(@"Requesting URI 2 ...");
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"Requesting URI 3 ...");
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"Requesting URI 4 ...");
return json_string;
}
Upvotes: 0
Views: 295
Reputation: 86651
Are you absolutely certain that response
is not nil? If your request to Google or wherever fails, response will be set to nil and the error will contain some information that will help you diagnose the error so change
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
to
NSError* error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (response == nil)
{
NSLog(@"request failed with error %@", error);
// any other error handling
}
Next thing. The default encoding for an HTTP message is ISO-8859-1, not UTF-8. According to Apple's docs, -initWithData: will return nil if the encoding is wrong. You probably want NSISOLatin1StringEncoding. I say "probably" because HTTP has a mechanism for telling you what character encoding it used. I think it's the header Content-Transfer-Encoding but I advise you to Google the HTTP RFC to find out for sure.
Finally if json_string were not nil, it would be leaking. Because you obtained it with alloc, you own it which means you need to autorelease it before returning it from sendURL: This last point is not the cause of your problem, it is a separate bug in your code.
Upvotes: 3