問題描述
來自 URL 編碼問題的 NSArray (NSArray from URL encoding problem)
So I have the following code:
NSURL *baseURL = [NSURL URLWithString:@"http://www.baseurltoanxmlpage.com"];
NSURL *url = [NSURL URLWithString: @"page.php" relativeToURL:baseURL];
NSArray *array = [NSArray arrayWithContentsOfURL:url];
If the XML page is as follows:
<array><dict><key>City</key><string>Montreal</string></dict></array>
The array returns fine. However, if the XML file is as follows:
<array><dict><key>City</key><string>Montréal</string></dict></array>
The array returns null. I guess this has something to do with the special char "é". How would I deal with these characters? The XML page is generated with PHP. utf8_encode() function makes the array return but then I don't know how to deal with the encoded "é" character.
Here's the working solution:
NSString *stringArray = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *array = [stringArray propertyList];
NSLog(stringArray);
NSLog(@"%@", array);
NSLog([[[array objectAtIndex:0] valueForKey:@"City"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
The first log prints out the "é" fine. In the second log, it's encoded and is printed as "\U00e9". In the 3rd log, it's decoded and printed as "é" (which is what I was looking for).
參考解法
方法 1:
As you noted, you need to return a UTF8- or UTF16-encoded XML document. Then make NSString
objects using the stringByReplacingPercentEscapesUsingEncoding:
method, using the relevant encoding.
方法 2:
NSString has a method to return data in encoding, data read from the URL:
+(id)stringWithContentsOfURL:encoding:error:
Look under String Encodings section for possible encodings to find the one suitable.
方法 3:
Looking at the NSString
documentation for :propertyList
, we see:
Parses the receiver as a text representation of a property list, returning an NSString, NSData, NSArray, or NSDictionary object, according to the topmost element.
A property list is an Apple-specific document that stores representations of NSString
, NSDictionary
, NSArray
, and other core types in XML format. These .plist
files are usually used for storing preferences or application settings.
This XML-formatted property list document is encoded in UTF-8, by default. When you turn your NSString
into a property list element, encoding the "é"
character replaces it with the UTF-8 Unicode character "\U00e9"
.
(by samvermette、Alex Reynolds、stefanB、Alex Reynolds)