URL支持26個(gè)英文字母、數(shù)字和少數(shù)幾個(gè)特殊字符六剥,當(dāng)URL中包含非標(biāo)準(zhǔn)的字符時(shí)晚顷,就需要對(duì)其進(jìn)行UTF8編碼,如果包含特殊字符會(huì)會(huì)造成NSURL出錯(cuò)疗疟,初始化為NULL该默,iOS中解決NSURL的初始化出錯(cuò)有兩種方法:
- (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.reibang.com/users/24da48b2ddb3/latest_articles";
NSURL *url=[NSURL URLWithString:str];
NSLog(@"URL:%@",url);
str=@"http://www.reibang.com/users/24da48b2ddb3/ latest_articles";
NSLog(@"特殊URL:%@",[NSURL URLWithString:str]);
str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"特殊URL:%@",[NSURL URLWithString:str]);
str=[@"http://www.reibang.com/users/24da48b2ddb3/ latest_articles" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"特殊URL:%@",[NSURL URLWithString:str]);