iOS URLEncode

之前的 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 URLEncode_第1张图片
警告内容

于是换成了新的实现( 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
    }
}

参考资料

  • Swift - encode URL
  • Objective-C url encoding

你可能感兴趣的:(iOS URLEncode)