iOS URLEncode

作者: 公爵海恩庭斯 | 来源:发表于2016-04-21 16:58 被阅读14170次

    之前的 URLEncode 实现收到了 Xcode 的黄警告:

    - (NSString *)URLDecode
    {
        return [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    
    - (NSString *)URLEncode
    {
        return [self urlEncodeUsingEncoding:NSUTF8StringEncoding];
    }
    
    - (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding
    {
        return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                   NULL,
                                                                   (__bridge CFStringRef)self,
                                                                   NULL,
                                                                   (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                   CFStringConvertNSStringEncodingToEncoding(encoding)));
    }
    
    警告内容

    于是换成了新的实现( iOS 7 和更高):

    extension String {
        // URL Decode
        func URLDecode() -> String? {
            return self.stringByRemovingPercentEncoding // `stringByReplacingPercentEscapesUsingEncoding` is deprecated
        }
        
        // URL Encode
        func URLEncode() -> String? {
            return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "!*'\"();:@&=+$,/?%#[]% ").invertedSet) // `CFURLCreateStringByAddingPercentEscapes` is deprecated
        }
    }
    

    参考资料

    相关文章

      网友评论

        本文标题:iOS URLEncode

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