Skip to content

Instantly share code, notes, and snippets.

@Tulakshana
Created June 8, 2017 12:28
Show Gist options
  • Save Tulakshana/e0c2c4ae1f26e46b0db3578e02439564 to your computer and use it in GitHub Desktop.
Save Tulakshana/e0c2c4ae1f26e46b0db3578e02439564 to your computer and use it in GitHub Desktop.
This method will mimic javascript function "encodeURIComponent(<string to be encoded>)" in Objective C
+ (NSString *) encodeString: (NSString *) string {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[string UTF8String];
int sourceLen = (int)strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"%20"];
} 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