Search code examples
iphoneobjective-cxmlnsmutableurlrequest

iphone: NSMutableURLRequest returns strange characters for MS Word style apostrophe


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];

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...