Skip to content

Instantly share code, notes, and snippets.

@pentiumao
Last active August 29, 2015 14:22
Show Gist options
  • Save pentiumao/577571874dfc381c4f38 to your computer and use it in GitHub Desktop.
Save pentiumao/577571874dfc381c4f38 to your computer and use it in GitHub Desktop.
iOS URL Encode: Unfortunately, stringByAddingPercentEscapesUsingEncoding doesn't always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash / and ampersand &) alone.
- (NSString *)urlEncode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment