Search code examples
iphonexmlencode

Sending encoded XML to a server from iPhone


I'm communicating between an iPhone app and a server using XML. To get around the problem of the user entering any character that might break the XML before I send it to the server i'm using the NSString method:

[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

But I noticed when doing a log of the string that the & symbol is not escaped? I thought that it should be? spaces, quotation marks and hash symbols which I've tested for all encode fine but not the ampersands?

What is the most common methods used for encoding/decoding XML sent to/received from a server?

Thanks.


Solution

  • The answer provided by @sleepy is a good approach, or if you prefer the syntax of implementing this in a category see this link for an example.

    Note that you should need to do this only for characters you are sending to the server via the URL parameters. If you are actually POST'ing XML data to the service by placing the XML content into the HTTP body of your request, then this kind of encoding is not needed. Depending on the size of the XML to be posted and the interface supported by your service, using the HTTP body might be a better choice in some scenarios.

    As an example of how to do this in the HTTP body, I typically use something like this:

    NSData *requestData = [requestXml dataUsingEncoding:NSUTF8StringEncoding];
    NSString *requestLength = [NSString stringWithFormat:@"%d", [requestXml length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serviceURL];    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
    [request setValue:requestLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:requestData];
    

    where requestXML is an NSString containing the XML I want to post and serviceURL is an NSURL for the service URL. In this case I am using UTF encoding for my XML content, which is what you should probably be using in all cases unless you have a specific reason not to.