Question

We are pulling content off our website using XML/NSMutableURLRequest and sometimes it pulls through the "curly" style apostrophe and quotes, ’ rather than '. NSMutableURLRequest seems to hate these and turns them into the strange \U00e2\U0080\U0099 string.

Is there something that I can to do prevent this? I am using the GET method, so should I be somehow telling it to use UTF-8? Or, am I missing something?

UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = YES;

    NSString *urlStr = [NSString stringWithFormat:@"%@",url];
    NSURL *serviceUrl = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
    [serviceRequest setHTTPMethod:@"GET"];

    NSURLResponse *serviceResponse;
    NSError *serviceError;

    app.networkActivityIndicatorVisible = NO;

    return [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
Was it helpful?

Solution

NSURLConnection returns an NSData response. You can take that NSData response and turn it into a string. Then take this string, turn it back into a NSData object, properly UTF-8 encoding it along the way, and feed it to NSXMLParser.

Example: (Assuming response is the NSData response from your request)

// long variable names for descriptive purposes
NSString* xmlDataAsAString = [[[NSString alloc] initWithData:response] autorelease];
NSData* toFeedToXMLParser = [xmDataAsAString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser* parser = [[[NSXMLParser alloc] initWithData:toFeedToXMLParser] autorelease];
// now utilize parser...

OTHER TIPS

I would suggest replacing those characters using stringByReplacingCharactersInRange:withString: to replace the unwanted strings.

NSString *currentTitle = @"Some string with a bunch of stuff in it.";

//Create a new range for each character.
NSRange rangeOfDash = [currentTitle rangeOfString:@"character to replace"];
NSString *location = (rangeOfDash.location != NSNotFound) ? [currentTitle substringToIndex:rangeOfDash.location] : nil;

if(location){
    currentTitle = [[currentTitle stringByReplacingOccurrencesOfString:location withString:@""] mutableCopy];
}

I've done this in the past to handle the same problem you describe.

Try using the stringByReplacingPercentEscapesUsingEncoding:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top