一共有五步,一步都不能少
-
1,创建请求地址
-
2,创建请求类
-
3,创建会话
-
4,根据会话创建任务
-
5,启动任务
-
Get方法
见代码
//1,创建请求地址
NSString *urlString = [NSString stringWithFormat:@"http://api.k780.com/?app=weather.future&weaid=%@&appkey=44509&sign=3fc6d1d99c68457934f71a4f0e99b7a2&format=json", @"beijing"];
//对字符进行处理
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlString];
//2.创建请求类
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.创建会话(单例)
NSURLSession *sharedSession = [NSURLSession sharedSession];
//4.根据会话创建任务
NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//这里是在子线程中执行的
if(data){
//请求到的数据,解码后可能是字典或是数组,可以用id类型的进行接收
id objc = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//打印数据
NSLog(@"%@", objc);
}
else{
NSLog(@"error = %@",error);
}
//若要进行一些UI操作,需要回到主线程中进行
//回到主线程
// [self performSelectorOnMainThread:@selector(selector) withObject:self waitUntilDone:(BOOL)];
}];
//5.启动任务
[dataTask resume];
回归主线程的方法
//回到主线程
// 1.
// [self performSelectorOnMainThread:(nonnull SEL) withObject:(nullable id) waitUntilDone:(BOOL)];
// 2.
// dispatch_async(dispatch_get_main_queue(), ^{
//
// });
// 3.
// [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//
// }];
- 协议方法
如果需要在网络请求数据的过程中,要做进一步的处理的话,就会用到代理
协议方法的话,要遵守协议
//遵守此协议
<NSURLSessionDataDelegate>
//接收数据
@property (nonatomic, strong) NSMutableData *data;
...........
...........
............
-(void)creatDataTask {
//1.创建请求地址
NSURL *url = [NSURL URLWithString:LIST_URL];
// 2.创建请求类
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.创建会话
// delegateQueue表示协议方法在哪个线程中执行
// NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// 4.创建任务
// NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
// //5.启动任务
// [dataTask resume];
}
//协议函数
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
NSLog(@"didReciveResponse");
if (self.data == nil) {
self.data = [[NSMutableData alloc] init];
} else {
self.data.length = 0; //让之前的数据清空
}
// NSURLSessionResponseCancel 默认 请求之后不接收服务器的数据
// NSURLSessionResponseAllow = 1,允许接收服务器的数据
// NSURLSessionResponseBecomeDownload = 2, 转成下载任务
// NSURLSessionResponseBecomeStream。//转成流
completionHandler(NSURLSessionResponseAllow);
}
//接收到数据,此函数调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSLog(@"didReceiveData");
//将数据拼接起来
[self.data appendData:data];
}
//数据请求完成或者请求错误调用的方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"didCompleteWithError");
if (error == nil) {
id objc = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
//打印数据
NSLog(@"%@", objc);
}
}