URL不受支持的解决

it2022-05-09  57

 

在网络请求中,URL中如果包含中文或者带空格的英文, 不处理会直接崩溃 

方法一:

NSURL * url =[NSURL URLWithString:[@"http://op.juhe.cn/onebox/football/league?dtype=json&league=中超&key=90b6d18361e00ed9c28b4d14e000f4ef" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];

方法二:

[@"" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

方法三:

[@"" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }]; [task resume];

 

注:方法二和方法三在iOS9.0之后已经放弃使用了,apple建议我们使用第一种方法。

方法一的使用:

- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters NS_AVAILABLE(10_9, 7_0);

NSCharacterSet是字符集,在NSURL.h中可以看到下面的代码:

@interface NSCharacterSet (NSURLUtilities) + (NSCharacterSet *)URLUserAllowedCharacterSet NS_AVAILABLE(10_9, 7_0); + (NSCharacterSet *)URLPasswordAllowedCharacterSet NS_AVAILABLE(10_9, 7_0); + (NSCharacterSet *)URLHostAllowedCharacterSet NS_AVAILABLE(10_9, 7_0); + (NSCharacterSet *)URLPathAllowedCharacterSet NS_AVAILABLE(10_9, 7_0); + (NSCharacterSet *)URLQueryAllowedCharacterSet NS_AVAILABLE(10_9, 7_0); + (NSCharacterSet *)URLFragmentAllowedCharacterSet NS_AVAILABLE(10_9, 7_0);

 

 

2016-08-13

转载于:https://www.cnblogs.com/zhengxinhong/p/5768719.html

相关资源:数据结构—成绩单生成器

最新回复(0)