Sunday, May 19, 2013

NSString stringByReplacingPercentEscapesUsingEncoding example ios


[NSString stringByReplacingPercentEscapesUsingEncoding]

Returns a new string made by replacing in the receiver all percent escapes with the matching characters as determined by a given encoding.
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
Parameters
encoding
The encoding to use for the returned string.
Return Value of [NSString stringByReplacingPercentEscapesUsingEncoding]
A new string made by replacing in the receiver all percent escapes with the matching characters as determined by the given encoding encoding. Returns nil if the transformation is not possible, for example, the percent escapes give a byte sequence not legal in encoding.
Discussion
See CFURLCreateStringByReplacingPercentEscapes for more complex transformations.
Example of [NSString stringByReplacingPercentEscapesUsingEncoding]
NSString *path = [[@"path+with+spaces"
    stringByReplacingOccurrencesOfString:@"+" withString:@" "]
    stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Example of [NSString stringByReplacingPercentEscapesUsingEncoding]
@interface NSString (stringByDecodingURLFormat)
- (NSString *)stringByDecodingURLFormat;
@end

@implementation NSString
- (NSString *)stringByDecodingURLFormat
{
    NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}
@end
Example of [NSString stringByReplacingPercentEscapesUsingEncoding]
NSString *input = @"Hello%20World";
NSString *output = [text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@ becomes %@",input,output);

Log: Hello%20World becomes Hello World