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 looks like this:

<array><dict><key>City</key><string>Montreal</string></dict></array>

      

The array returns a penalty. However, if the XML file looks like this:

<array><dict><key>City</key><string>Montréal</string></dict></array>

      

The array returns null. I'm guessing it has something to do with the special char "é". How will I deal with these characters? The XML page is generated using PHP. The utf8_encode () function returns an array, but then I don't know how to handle the encoded character "é".

Here's a 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 magazine prints out "é" fine. In the second magazine, it is encoded and printed as "\ U00e9". In the third magazine, it is decoded and printed as "é" (which is what I was looking for).

+1


a source to share


3 answers


As you noted, you need to return a UTF8- or UTF16 encoded XML document. Then create the objects NSString

using the method stringByReplacingPercentEscapesUsingEncoding:

using the appropriate encoding.



+2


a source


NSString has a method to return data in encoding , data read from a URL:

+ (ID) stringWithContentsOfURL: encoding: error:



Look under String Encodings for possible encodings to find a suitable one.

+1


a source


Looking at the documentation NSString

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 list of properties is a document specific to Apple, which stores a representation of NSString

, NSDictionary

, NSArray

and other basic types in XML format. These files .plist

are commonly used to store preferences or application settings.

This XML format property sheet document is by default encoded in UTF-8 . When you turn yours NSString

into a property list item, the character encoding "é"

replaces it with a Unicode UTF-8 character"\U00e9"

.

0


a source







All Articles