开发者

urldecode in objective-c

开发者 https://www.devze.com 2023-02-04 15:41 出处:网络
I\'m dealing with an urlencoded string in objective-c. Is there a foundation function that actually reverse the urlENCODING?

I'm dealing with an urlencoded string in objective-c. Is there a foundation function that actually reverse the urlENCODING?

The stri开发者_Python百科ng received is like: K%FChlschrank but should be after decoding Kühlschrank


I made a quick category to help resolve this :)

@interface NSString (stringByDecodingURLFormat)
- (NSString *)stringByDecodingURLFormat;
@end

@implementation NSString
- (NSString *)stringByDecodingURLFormat
{
    NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}
@end

Once defined, this quickly can handle an encoded string:

NSString *decodedString = [myString stringByDecodingURLFormat];

Plenty of other ways to implement.


I believe this is what you are looking for:

- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

Return Value:

A new string made by replacing in the receiver all percent escapes with the matching characters as determined by the given encoding. It returns nil if the transformation is not possible, for example, the percent escapes give a byte sequence not legal in encoding.

[source: Apple NSString Class Reference]


Apple has depreacted stringByReplacingPercentEscapesUsingEncoding: since iOS9. Please use stringByRemovingPercentEncoding.

The new method, Returns a new string made from the receiver by replacing all percent-encoded sequences with the matching UTF-8 characters.

Example:

NSString *encodedLink = @"hello%20world";
NSString *decodedUrl = [encodedLink stringByRemovingPercentEncoding];
NSLog (@"%@", decodedUrl);

Output:

hello world


- (NSString *)URLDecode:(NSString *)stringToDecode
{
    NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

That's it


According to W3Schools, URLs can only be sent over the Internet using the ASCII character set. For me this piece of code worked:

NSString *original = @"K%FChlschrank";

NSString *result2 = [original stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];


For parmanent solution on iOS 9, use fallowing code

NSURL* link = [NSURL URLWithString:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
0

精彩评论

暂无评论...
验证码 换一张
取 消