美文网首页
ios中URL字符串的URLencode与URLdecode

ios中URL字符串的URLencode与URLdecode

作者: 二斤寂寞 | 来源:发表于2018-05-21 18:38 被阅读22次

    ios中url经常需要进行encode、decode处理,废话不多,直接高清无码,直逼问题!!!

    第一种:比较陈旧

    //URLEncode
    + (NSString*) encodeString:(NSString*)unencodedString {
        
        // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
        // CharactersToLeaveUnescaped = @"[].";
        
        NSString *encodedString = (NSString *)
        CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                  (CFStringRef)unencodedString,
                                                                  NULL,
                                                                  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                  kCFStringEncodingUTF8));
        
        return encodedString;
    }
    
    //URLDEcode
    -(NSString *)decodeString:(NSString*)encodedString
    
    {
        //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
        NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                         (__bridge CFStringRef)encodedString,
                                                                                                                         CFSTR(""),
                                                                                                                         CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
        return decodedString;
    }
    

    第二种:ios7.0之后

    //encode
    [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //decode
    [string stringByRemovingPercentEncoding];
    

    第三种:自定义
    NSCharacterSet系统内置的一些返回CharacterSet 的方法

    • URLFragmentAllowedCharacterSet "#%<>[]^`{|}
    • URLHostAllowedCharacterSet "#%/<>?@^`{|}
    • URLPasswordAllowedCharacterSet "#%/:<>?@[]^`{|}
    • URLPathAllowedCharacterSet "#%;<>?[]^`{|}
    • URLQueryAllowedCharacterSet "#%<>[]^`{|}
    • URLUserAllowedCharacterSet "#%/:<>?@[]^`
    NSCharacterSet *chaSet = [NSCharacterSet characterSetWithCharactersInString:@"'();:@&=+$,/?%#[]"]; 
    [string stringByAddingPercentEncodingWithAllowedCharacters:chaSet];
    

    相关文章

      网友评论

          本文标题:ios中URL字符串的URLencode与URLdecode

          本文链接:https://www.haomeiwen.com/subject/freqjftx.html