Question

I am working on an IOS application that needs to communicate with an API (CloudStack). The API requires that each request is signed.

I need to URL encode the parameters and create an HMAC SHA1 hash. Everything works fine until I pass an parameter that contains an plus sign or an colon.

So I guess it is the URL encoding part of my application that isn't working correct. I've searched several sites and tried the provided solutions but without any results.

One of the API specifications is that all the spaces needs to be encoded as "%20" rather than "+".

The API signing guide: http://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.1.0/html/Developers_Guide/signing-api-requests.html

Currently I am using the following code to URL encode the URL:

-(NSString *)urlenc:(NSString *)val
{    
    NSString *result = [(NSString *)val stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    return result;
}

I call the method like this: [self urlenc@"2014-01-20T14:02:48+0100"]

Was it helpful?

Solution

In your case the problem probably is both the "+" and ":" character that stringByAddingPercentEscapesUsingEncoding does not encode.

You need to use an encoder that supports more characters, see this SO answer for more complete information.

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding encodes 14 characrters:

`#%^{}[]|\"<> plus the space character as percent escaped.

Here is sample code (iOS7 and above, otherwise see this SO answer):
You may need to change the characters that are encoded.

NSString *testString = @"2014-01-20T14:02:48+0100";
NSString *encodedString1 = [testString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"encodedString1: %@", encodedString1);

NSString *charactersToEscape = @"!*'();:@&=+$,/?%#[]\" ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *encodedString2 = [testString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(@"encodedString2: %@", encodedString2);

NSLog output:

encodedString1: 2014-01-20T14:02:48+0100
encodedString2: 2014-01-20T14%3A02%3A48%2B0100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top