控制器銷毀后一定要釋放NSURLSession
因為它是單例不會被銷毀 所以它所開啟的任務(wù)也都不會被銷毀 要自己手動釋放
- (void)dealloc{
[_session invalidateAndCancel];
}
下載圖片
UIImage* image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=440867696,2376631565&fm=173&s=677059CAD826990FFCB4203303008050&w=640&h=427&img.JPEG"]]];
NSURLSession網(wǎng)絡(luò)請求
注意 如果完成請求后需要更新UI需要獲取主線程進行操作 因為網(wǎng)絡(luò)請求是在子線程進行的
NSURL *url = [NSURL URLWithString:@"http://localhost:3002/test"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSData *postData = [@"name=vijay" dataUsingEncoding:NSUTF8StringEncoding] ;
// 把字符參數(shù)轉(zhuǎn)換成UTF8類型的字符串 form-data的post參數(shù)都是xxx=xxx的 瀏覽器開發(fā)者工具顯示的xx:xx是為了好看
request.HTTPBody = postData;
NSLog(@"%@",[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
NSLog(@"%@",response);
NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}
}];
[task resume];
設(shè)置NSURLSession代理
// 創(chuàng)建一個自定義配置的session 設(shè)置代理和回調(diào)要用的線程
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
//不能用block回調(diào) 如果用回調(diào)代理方法則不生效
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
下載文件
//
// ViewController.m
// GCD
//
// Created by 杰王 on 2017/12/2.
// Copyright ? 2017年 杰王. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<NSURLSessionTaskDelegate>
@property (nonatomic,strong) UIImage* image1;
@property (nonatomic,strong) UIImage* image2;
@property (nonatomic,strong) NSOutputStream* outStream;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self network];
}
- (void)network{
NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512260152935&di=3abfd233dfbb7e6f0e2c341012458a05&imgtype=0&src=http%3A%2F%2Fimages.trvl-media.com%2Fhotels%2F4000000%2F3900000%2F3893200%2F3893187%2F3893187_25_y.jpg"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
[[session dataTaskWithURL:url] resume];
}
#pragma mark - <NSURLSessionTaskDelegate>
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
[_outStream close];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data{
[_outStream write:data.bytes maxLength:data.length];
}
/* Sent when a download has been resumed. If a download failed with an
* error, the -userInfo dictionary of the error will contain an
* NSURLSessionDownloadTaskResumeData key, whose value is the resume
* data.
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:@"xxx.jpg"];
NSLog(@"%@",filePath);
_outStream = [[NSOutputStream alloc ] initToFileAtPath:filePath append:YES];
[_outStream open];
completionHandler(NSURLSessionResponseAllow);
}
@end