NSURLSession
- 使用步骤
- 创建NSURLSession的会话
- 根据会话创建Task
- 执行Task
- Task的类型
- NSURLSessionTask:是一个抽象类,不能直接使用
- NSURLSessionDataTask:请求与数据相关,可以直接使用
- NSURLSessionDownloadTask:与下载相关,可以直接使用
- NSURLSessionUploadTask:与上传相关,可以直接使用
具体代码
需求是在用户进行输入的时候产生联想效果,所以对textfiled进行了监听
@interface SearchViewController ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, NSURLSessionDataDelegate>//设置协议
//接收服务器返回的数据
@property(nonatomic, strong)NSMutableData *data;
@end
@implementation SearchViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIImage *background = [UIImage imageNamed:@"背景.JPG"];
self.view.layer.contents = (id)background.CGImage;
//设置TextField
_searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(25, 50, 330, 40)];
[self.view addSubview:_searchTextField];
_searchTextField.placeholder = @"请输入城市信息";
_searchTextField.delegate = self;
[_searchTextField setBorderStyle:UITextBorderStyleRoundedRect];
_searchTextField.keyboardType = UIKeyboardTypeDefault;
_searchTextField.backgroundColor = [UIColor clearColor];
//初始化数组
if (_cityArray == nil) {
_cityArray = [[NSMutableArray alloc] init];
}
if(_numArray == nil){
_numArray = [[NSMutableArray alloc] init];
}
}
//监听textField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(string != nil && _searchTextField.text != NULL){
NSString * str = [_searchTextField.text stringByAppendingString:string];
//网络请求
[self creatUrl:str];
}
_cityArray = [[NSMutableArray alloc] init];
_numArray = [[NSMutableArray alloc] init];
//显示文本内容
return YES;
}
-(void)creatUrl:(NSString *)str{
//地址
NSString *strName = [NSString stringWithFormat:@"https://geoapi.heweather.net/v2/city/lookup?location=%@&key=fbd7d8d089284f159aeeec08fd63985f", str];
//中文空格字符编码/解码
strName = [strName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//设置请求的地址
NSURL *url = [NSURL URLWithString:strName];
//封装一个请求类
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//1.创建Session会话
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//2.根据会话创建任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
//3.启动任务
[dataTask resume];
}
//接收到服务器的响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler{
//拼接返回的数据
//从未使用时初始化data
if(self.data == nil){
self.data = [[NSMutableData alloc] init];
}
//如果之前有数据,则清空
else {
self.data.length = 0;
}
//允许接收数据
completionHandler(NSURLSessionResponseAllow);
/*
SURLSessionResponseCancel = 0, 默认 请求后不接收服务器的数据
NSURLSessionResponseAllow = 1, 允许接收服务器数据
NSURLSessionResponseBecomeDownload = 2, 专成下载任务
NSURLSessionResponseBecomeStream 专成流
*/
}
//接收到数据时调用,会被调用多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
//拼接数据
[self.data appendData:data];
}
//数据请求完成 或请求出现错误时调用
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
//请求成功
if (error == nil) {
//解析数据
NSDictionary *oneDictionary = [NSJSONSerialization JSONObjectWithData:self.data options:kNilOptions error:nil];
_cityArray = [[NSMutableArray alloc]init];
_numArray = [[NSMutableArray alloc]init];
NSArray *timeArray = [[NSArray alloc]init];
//对需要用到的数据进行赋值
timeArray = oneDictionary[@"location"];
for (int i = 0; i < timeArray.count; i++) {
NSString * str = oneDictionary[@"location"][i][@"name"];
NSString * numberStr = oneDictionary[@"location"][i][@"id"];
[_cityArray addObject:str];
[_numArray addObject:numberStr];
}
}
//回归到主线程(要进行UI操作)
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self->_tableView reloadData];
}];
}
第一次学习网络请求,了解的还不够深入,如果有不正确的地方,欢迎纠正