ios9弃用方法替换
iOS平台在快速的发展,各种接口正在不断的更新。随着iOS9的发布,又有一批老方法不推荐使用了,你若调用这些方法,运行的结果是没有问题的,但是会出现警告“**is deprecated :first deprecated in iOS 9.0 - Use ………”.:
在实际项目开发中,我们要秉承一个信念就是:要把每一个警告当做错误来处理,并解决每一个警告。你想想,你运行一个项目,就算运行成功了,但是出现几十个、甚至几百个黄黄的警告,心情是不是很糟糕呢?我将在这篇博客结合我的开发经验,罗列出iOS9中不推荐使用的方法,并换成苹果最新推荐的方式。本篇博客将会持续更新。
1.弹出提示对话框
在iOS9之前我们使用AlertView来弹出对话框,现在推荐使用AlertController,对于这个变化,请参考我的另一篇博客《iOS9使用提示框的正确实现方式》。
2.字符串编码的修改
ios9以前
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ios9以后
第一种编码好长
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
第二种编码
NSURL *url = [NSURL URLWithString:[urlStr stringByRemovingPercentEncoding]];
3.【NSURLSession替换NSURLConnection】
ios9之前使用方法
----------
//以下方法已经被禁用;
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
NSData *data = [[param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
// 非代理异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
YYLog(@"%@",connectionError);
}
if(data)
{}
}
ios9之后使用方法
----------
NSURL *url = [NSURL URLWithString:[urlStr stringByRemovingPercentEncoding]];
//创建请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
NSData *data = [[param stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
//创建session对象
NSURLSession * session = [NSURLSession sharedSession];
// NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfiguration];
//添加任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable connectionError) {
if (connectionError) {
}
if(data)
{ }
}];
//开始任务
[dataTask resume];