YosiFZ
YosiFZ

Reputation: 7900

NSMutableData to NSString give nil

I am using my app NSURLConnection for getting webpage of a site.

this how i call the NSURLConnection

NSURL *url = [NSURL URLWithString:@"http://jokes.moment.co.il/default.asp?s1=4&s2=0"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];

this is how i append the data that i get:

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (receivedData)
    {
        [receivedData appendData:data];
    }
    else 
    {
        receivedData = [[NSMutableData alloc] initWithData:data];
    }
}

and this is how i try to convert it to NSString:

-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
}

the receivedData is 47586 bytes and when i do the convert the string is nil

Upvotes: 2

Views: 902

Answers (2)

mmccomb
mmccomb

Reputation: 13807

A quick look at the content for your URL show that the content-type is ISO-8859-1

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

Try changing your call to initWithData to...

[[NSString alloc] initWithData:nsdata encoding:NSISOLatin1StringEncoding];

Upvotes: 6

bbum
bbum

Reputation: 162712

More likely than not, the received string is not validly encoded as NSUTF8StringEncoding.

You may need to write the string to the filesystem and then use one of the NSString methods that describes any conversion errors via an NSError** argument to know the exact error.

Upvotes: 1

Related Questions