Last active
August 29, 2015 14:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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