1.GET請求
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
2.POST請求
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
request.HTTPMethod = @"POST"; // 請求方法
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; // 請求體
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
3.下載
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 獲得下載任務(wù)
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 文件將來存放的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
// 啟動任務(wù)
[task resume];
4.NSURLSession的代理方法
#import "ViewController.h"
@interface ViewController () <NSURLSessionDataDelegate, NSURLConnectionDataDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]]];
// 啟動任務(wù)
[task resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到服務(wù)器的響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"%s", __func__);
// 允許處理服務(wù)器的響應(yīng)跃赚,才會繼續(xù)接收服務(wù)器返回的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
// void (^)(NSURLSessionResponseDisposition)
}
/**
* 2.接收到服務(wù)器的數(shù)據(jù)(可能會被調(diào)用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"%s", __func__);
}
/**
* 3.請求成功或者失敶取(如果失敗蚪腋,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __func__);
}
@end
5.大文件下載
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self download];
}
- (void)download
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 獲得下載任務(wù)
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// 啟動任務(wù)
[task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"didResumeAtOffset");
}
/**
* 每當(dāng)寫入數(shù)據(jù)到臨時文件時琐旁,就會調(diào)用一次這個方法
* totalBytesExpectedToWrite:總大小
* totalBytesWritten: 已經(jīng)寫入的大小
* bytesWritten: 這次寫入多少
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
/**
*
* 下載完畢就會調(diào)用一次這個方法
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// 文件將來存放的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
@end
6.大文件斷點下載
// resumeData的文件路徑
#define XMGResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmp"]
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
/** 保存上次的下載信息 */
@property (nonatomic, strong) NSData *resumeData;
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
//- (NSData *)resumeData
//{
// if (!_resumeData) {
// _resumeData = [NSData dataWithContentsOfFile:XMGResumeDataFile];
// }
// return _resumeData;
//}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
// if (self.resumeData) {
// // 獲得上次的下載任務(wù)
// self.task = [self.session downloadTaskWithResumeData:self.resumeData];
//
// // 將上次的臨時文件放到tmp中
//
// } else {
// 獲得下載任務(wù)
self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// }
// 啟動任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
// 一旦這個task被取消了祟牲,就無法再恢復(fù)
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
//
// // 可以將resumeData寫入沙盒,保存起來
// // 下次進入程序,就可以將resumeData讀取進來,繼續(xù)下載
// [resumeData writeToFile:XMGResumeDataFile atomically:YES];
//
// // caches文件夾
// NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//
// // 緩存文件
// NSString *tmp = NSTemporaryDirectory();
// NSFileManager *mgr = [NSFileManager defaultManager];
// NSArray *subpaths = [mgr subpathsAtPath:tmp];
// NSString *file = [tmp stringByAppendingPathComponent:[subpaths lastObject]];
// NSString *cachesTempFile = [caches stringByAppendingPathComponent:[file lastPathComponent]];
// [mgr moveItemAtPath:file toPath:cachesTempFile error:nil];
//
// [@{@"tempFile" : cachesTempFile} writeToFile:[caches stringByAppendingPathComponent:@"tempFile.plist"] atomically:YES];
}];
}
/**x
請求這個路徑:http://120.25.226.186:32812/resources/videos/minion_01.mp4
設(shè)置請求頭
Range : 1024-2000
*/
/**
* 繼續(xù)下載
*/
- (IBAction)goOn:(id)sender {
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
// 保存恢復(fù)數(shù)據(jù)
self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"didResumeAtOffset");
}
/**
* 每當(dāng)寫入數(shù)據(jù)到臨時文件時王浴,就會調(diào)用一次這個方法
* totalBytesExpectedToWrite:總大小
* totalBytesWritten: 已經(jīng)寫入的大小
* bytesWritten: 這次寫入多少
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
/**
*
* 下載完畢就會調(diào)用一次這個方法
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// 文件將來存放的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
@end
7.文件上傳
#define XMGBoundary @"520it"
#define XMGEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define XMGNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
#import "ViewController.h"
@interface ViewController ()
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
cfg.timeoutIntervalForRequest = 10;
// 是否允許使用蜂窩網(wǎng)絡(luò)(手機自帶網(wǎng)絡(luò))
cfg.allowsCellularAccess = YES;
_session = [NSURLSession sessionWithConfiguration:cfg];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];
request.HTTPMethod = @"POST";
// 設(shè)置請求頭(告訴服務(wù)器,這是一個文件上傳的請求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];
// 設(shè)置請求體
NSMutableData *body = [NSMutableData data];
// 文件參數(shù)
// 分割線
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 文件參數(shù)名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:XMGNewLine];
// 文件的類型
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:XMGNewLine];
// 文件數(shù)據(jù)
[body appendData:XMGNewLine];
[body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:XMGNewLine];
// 結(jié)束標(biāo)記
/*
--分割線--\r\n
*/
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGEncode(@"--")];
[body appendData:XMGNewLine];
[[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
}
@end
8.大文件下載(NSOutputStream)
// 文件的存放路徑(caches)
#define XMGMp4File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.mp4"]
#import "ViewController.h"
@interface ViewController () <NSURLSessionDataDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 寫文件的流對象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger contentLength;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
- (NSOutputStream *)stream
{
if (!_stream) {
_stream = [NSOutputStream outputStreamToFileAtPath:XMGMp4File append:YES];
}
return _stream;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", XMGMp4File);
[[NSFileManager defaultManager] removeItemAtPath:XMGMp4File error:nil];
}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
// 創(chuàng)建一個Data任務(wù)
self.task = [self.session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// 啟動任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
/**
* 繼續(xù)下載
*/
- (IBAction)goOn:(id)sender {
[self.task resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 打開流
[self.stream open];
// 獲得文件的總長度
self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
// 接收這個請求,允許接收服務(wù)器的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器返回的數(shù)據(jù)(這個方法可能會被調(diào)用N次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 寫入數(shù)據(jù)
[self.stream write:data.bytes maxLength:data.length];
// 目前的下載長度
NSInteger downloadLength = [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGMp4File error:nil][NSFileSize] integerValue];
// 下載進度
NSLog(@"%f", 1.0 * downloadLength / self.contentLength);
}
/**
* 3.請求完畢(成功\失斆吩场)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 關(guān)閉流
[self.stream close];
self.stream = nil;
}
@end
9.大文件斷點下載(NSOutputStream)
// 所需要下載的文件的URL
#define XMGFileURL @"http://120.25.226.186:32812/resources/videos/minion_01.mp4"
// 文件名(沙盒中的文件名)
#define XMGFilename XMGFileURL.md5String
// 文件的存放路徑(caches)
#define XMGFileFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:XMGFilename]
// 存儲文件總長度的文件路徑(caches)
#define XMGTotalLengthFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.xmg"]
// 文件的已下載長度
#define XMGDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGFileFullpath error:nil][NSFileSize] integerValue]
#import "ViewController.h"
#import "NSString+Hash.h"
#import "UIImageView+WebCache.h"
@interface ViewController () <NSURLSessionDataDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 寫文件的流對象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger totalLength;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
- (NSOutputStream *)stream
{
if (!_stream) {
_stream = [NSOutputStream outputStreamToFileAtPath:XMGFileFullpath append:YES];
}
return _stream;
}
- (NSURLSessionDataTask *)task
{
if (!_task) {
NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:XMGTotalLengthFullpath][XMGFilename] integerValue];
if (totalLength && XMGDownloadLength == totalLength) {
NSLog(@"----文件已經(jīng)下載過了");
return nil;
}
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// 設(shè)置請求頭
// Range : bytes=xxx-xxx
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 創(chuàng)建一個Data任務(wù)
_task = [self.session dataTaskWithRequest:request];
}
return _task;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", XMGFileFullpath);
}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
// 啟動任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 打開流
[self.stream open];
// 獲得服務(wù)器這次請求 返回數(shù)據(jù)的總長度
self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + XMGDownloadLength;
// 存儲總長度
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:XMGTotalLengthFullpath];
if (dict == nil) dict = [NSMutableDictionary dictionary];
dict[XMGFilename] = @(self.totalLength);
[dict writeToFile:XMGTotalLengthFullpath atomically:YES];
// 接收這個請求氓辣,允許接收服務(wù)器的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器返回的數(shù)據(jù)(這個方法可能會被調(diào)用N次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 寫入數(shù)據(jù)
[self.stream write:data.bytes maxLength:data.length];
// 下載進度
NSLog(@"%f", 1.0 * XMGDownloadLength / self.totalLength);
}
/**
* 3.請求完畢(成功\失敗)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 關(guān)閉流
[self.stream close];
self.stream = nil;
// 清除任務(wù)
self.task = nil;
}
@end
11.大文件斷點下載的另一種方法
// 文件的存放路徑(caches)
#define XMGMp4File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.mp4"]
// 文件的已下載長度
#define XMGDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGMp4File error:nil][NSFileSize] integerValue]
#import "ViewController.h"
@interface ViewController () <NSURLSessionDataDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 寫文件的流對象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger totalLength;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
- (NSOutputStream *)stream
{
if (!_stream) {
_stream = [NSOutputStream outputStreamToFileAtPath:XMGMp4File append:YES];
}
return _stream;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", XMGMp4File);
}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// 設(shè)置請求頭
// Range : bytes=xxx-xxx
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 創(chuàng)建一個Data任務(wù)
self.task = [self.session dataTaskWithRequest:request];
// 啟動任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
/**
* 繼續(xù)下載
*/
- (IBAction)goOn:(id)sender {
[self.task resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 打開流
[self.stream open];
// 獲得服務(wù)器這次請求 返回數(shù)據(jù)的總長度
self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + XMGDownloadLength;
// 接收這個請求袱蚓,允許接收服務(wù)器的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器返回的數(shù)據(jù)(這個方法可能會被調(diào)用N次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 寫入數(shù)據(jù)
[self.stream write:data.bytes maxLength:data.length];
// 下載進度
NSLog(@"%f", 1.0 * XMGDownloadLength / self.totalLength);
}
/**
* 3.請求完畢(成功\失敵ァ)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 關(guān)閉流
[self.stream close];
self.stream = nil;
}
@end