Question

I have an iOS application which is download from server an XML file encoded in Windows 1252.

I am using the following code to save it to my document folder :

NSString *path = @"http://server/file.xml";
    NSURL *URL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSWindowsCP1252StringEncoding]];
    NSData *xmlData = [NSData dataWithContentsOfURL:URL];
    if(xmlData == nil) {
        // Error - handle appropriately
        NSLog(@"ERROR");
    }
    NSString *applicationDocumentsDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *storePath=[applicationDocumentsDir stringByAppendingPathComponent:@"annonces.xml"];
    [xmlData writeToFile:storePath atomically:TRUE];
    NSLog(@"write xml");

It doesn't work, I've got an nil response when I try to read it with the parser. How could I do to get it properly. I cannot change the encoding of te xml which is on the server. If I change the XML encoding manually, I've got a correct response.

This is how I pass the XML string to parse it with XML Dictionnary class :

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *finalPath = [path stringByAppendingPathComponent:@"annonces.xml"];
    NSString *string = [[NSString alloc] initWithContentsOfFile:finalPath encoding:NSWindowsCP1252StringEncoding error:NULL];
    NSLog(@"string: %@", string);
    NSDictionary *items = [NSDictionary dictionaryWithXMLString:string];
    NSLog(@"dictionary: %@", items);
Was it helpful?

Solution

Your URL variable contains the url address of the location of the XML file you want to download.

However you are applying NSWindowsCP1252StringEncoding to the url, not to the content of the file.

xmlData is nil because dataWithContentsOfURL: cannot find the file at the location you have specified within URL.

You need to download the file first, then once its downloaded then you can be concerned about what encoding its in and how to parse it.

The way you are using NSWindowsCP1252StringEncoding has got nothing to do with the content of the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top