iOS 深度好文iOS精进

iOS URLEncode

2016-04-21  本文已影响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
    }
}

参考资料

上一篇下一篇

猜你喜欢

热点阅读