2011-01-25 36 views
4

我們正在使用XML/NSMutableURLRequest將內容從我們的網站上拉下來,有時它會通過「捲曲」式撇號和引號「而不是」拉動內容。 NSMutableURLRequest似乎討厭這些,並把它們變成奇怪的\ U00e2 \ U0080 \ U0099字符串。iphone:NSMutableURLRequest爲MS Word風格的撇號返回奇怪的字符

有什麼我可以做的,以防止這種情況?我正在使用GET方法,所以我應該以某種方式告訴它使用UTF-8?或者,我錯過了什麼?

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

你能張貼有關問題的代碼? – Alex 2011-01-25 18:58:59

+0

更新了我的帖子... – 2011-01-25 19:32:35

回答

5

NSURLConnection返回一個響應NSData。你可以把這個NSData響應變成一個字符串。然後取出該字符串,將其重新轉換爲一個NSData對象,正確編碼UTF-8,然後將其提供給NSXMLParser

例子:(假設response是從您的要求NSData響應)

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

我建議用stringByReplacingCharactersInRange:withString:替換那些字符來替換不需要的字符串。

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

我已經在過去做過這件事來處理您描述的相同問題。

+0

是的,但這只是爲了解決問題,不能阻止它。有沒有一種方法可以防止這一點呢? – 2011-01-25 19:31:30

0

嘗試使用stringByReplacingPercentEscapesUsingEncoding: