Search code examples
iosobjective-cnsstringnsurlconnectionnsdata

NSData to HTML NSString using NSURLConnection


I have a question about NSUrlConnection.

I tried to send request to an URL and I would to take the corresponding HTML.

I try with this code:

    [NSURLConnection sendAsynchronousRequest:urlRequest
                                           queue:queue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

     NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}];

I see the correct NSData but the NSString is nil. Have I some problem about encoding?


Solution

  • It is not necessary it returns string, as per documentation it could retrun nil if data encoding is not right.

    Return Value An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

    make sure your encoding is right.