URL支持26个英文字母、数字和少数几个特殊字符,当URL中包含非标准的字符时,就需要对其进行UTF8编码,如果包含特殊字符会会造成NSURL出错,初始化为NULL,iOS中解决NSURL的初始化出错有两种方法:
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc NS_DEPRECATED(10_0, 10_11, 2_0, 9_0, "Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.");
方法二:
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters NS_AVAILABLE(10_9, 7_0);
参考代码:
NSString *str=@"http://www.jianshu.com/users/24da48b2ddb3/latest_articles";
NSURL *url=[NSURL URLWithString:str];
NSLog(@"URL:%@",url);
str=@"http://www.jianshu.com/users/24da48b2ddb3/ latest_articles";
NSLog(@"特殊URL:%@",[NSURL URLWithString:str]);
str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"特殊URL:%@",[NSURL URLWithString:str]);
str=[@"http://www.jianshu.com/users/24da48b2ddb3/ latest_articles" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"特殊URL:%@",[NSURL URLWithString:str]);