iPhone: NSMutableURLRequest ritorna caratteri strani per MS Word stile apostrofo
-
24-10-2019 - |
Domanda
stanno tirando fuori i contenuti del nostro sito web utilizzando XML / NSMutableURLRequest ea volte tira attraverso l'apostrofo e le virgolette stile "riccio",’piuttosto che'. NSMutableURLRequest sembra odiare questi e li trasforma in quello strano \ U00e2 \ U0080 \ U0099 stringa.
C'è qualcosa che posso fare per evitare questo? Sto usando il metodo GET, quindi dovrei essere in qualche modo dicendogli di usare UTF-8? Oppure, mi sto perdendo qualcosa?
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];
Soluzione
NSURLConnection
restituisce una risposta NSData
. Si può prendere che la risposta NSData
e di trasformarlo in una stringa. Dai questa stringa, riattivarlo in un oggetto NSData
propriamente UTF-8 codifica lungo la strada, e mangimi per NSXMLParser
.
Esempio: (Assumendo response
è la risposta NSData
dalla richiesta)
// 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...
Altri suggerimenti
Vorrei suggerire di sostituire quei personaggi utilizzando stringByReplacingCharactersInRange:withString:
per sostituire le stringhe indesiderati.
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];
}
L'ho fatto in passato per gestire lo stesso problema che si descrive.
Provare a utilizzare lo stringByReplacingPercentEscapesUsingEncoding: