之前的 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
}
}
网友评论