URL encoding strings in Objective-C (works on iOS and Mac)
by Alex Stylianos
Some of the easiest things can be really hard in some languages. One of them is a simple way to properly escape a string in URL format, according to RFC 3986 section 2.3.
Many programmers refer to it as "percentage encoding".
Here is a simple function that does the job as it's supposed to for UTF-8 strings commonly used in the Internet.
- (NSString *)urlencode:(NSString *)input { const char *input_c = [input cStringUsingEncoding:NSUTF8StringEncoding]; NSMutableString *result = [NSMutableString new]; for (NSInteger i = 0, len = strlen(input_c); i < len; i++) { unsigned char c = input_c[i]; if ( (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c == '~' ) { [result appendFormat:@"%c", c]; } else { [result appendFormat:@"%%%02X", c]; } } return result; }