iphone: NSMutableURLRequest returns strange characters for MS Word style apostrophe

时光毁灭记忆、已成空白 提交于 2019-12-12 11:54:49

问题


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

回答1:


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



回答2:


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.




回答3:


Try using the stringByReplacingPercentEscapesUsingEncoding:



来源:https://stackoverflow.com/questions/4797574/iphone-nsmutableurlrequest-returns-strange-characters-for-ms-word-style-apostro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!