urldecode in objective-c

前端 未结 6 1731
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 10:19

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

The string received is like: K%FChlschr

相关标签:
6条回答
  • 2020-12-05 10:26
    - (NSString *)URLDecode:(NSString *)stringToDecode
    {
        NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
        result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return result;
    }
    

    That's it

    0 讨论(0)
  • 2020-12-05 10:32

    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]
    
    0 讨论(0)
  • 2020-12-05 10:41

    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
    
    0 讨论(0)
  • 2020-12-05 10:46

    For parmanent solution on iOS 9, use fallowing code

    NSURL* link = [NSURL URLWithString:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    
    0 讨论(0)
  • 2020-12-05 10:48

    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];
    
    0 讨论(0)
  • 2020-12-05 10:49

    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.

    0 讨论(0)
提交回复
热议问题