iOS - NSURLConnection&&NSURLSession

作者:Mitchell 

一、NSURLConnection

  • iOS7之后不建議使用
  • GET請求
    • 發(fā)送同步請求
    // 1.創(chuàng)建一個URL
    NSURL *url = [NSURL URLWithString:@"httpAddress"];
    // 2.根據(jù)URL創(chuàng)建NSURLRequest對象
    // 默認(rèn)情況下NSURLRequest會自動給我們設(shè)置好請求頭
    // request默認(rèn)情況下就是GET請求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3.利用NSURLConnection對象發(fā)送請求
    /*
     第一個參數(shù): 需要請求的對象
     第二個參數(shù): 服務(wù)返回給我們的響應(yīng)頭信息
     第三個參數(shù): 錯誤信息
     返回值: 服務(wù)器返回給我們的響應(yīng)體
     */
    //    NSURLResponse *response = nil;
    NSHTTPURLResponse *response = nil; // 真實(shí)類型
    // 注意點(diǎn): 如果是調(diào)用NSURLConnection的同步方法, 會阻塞當(dāng)前線程
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
  • 發(fā)送異步請求
    // 1.創(chuàng)建一個URL
    NSURL *url = [NSURL URLWithString:@"httpAddress"];
    // 2.根據(jù)URL創(chuàng)建NSURLRequest對象
    // 默認(rèn)情況下NSURLRequest會自動給我們設(shè)置好請求頭
    // request默認(rèn)情況下就是GET請求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 3.利用NSURLConnection對象發(fā)送請求
    /*
     第一個參數(shù): 需要請求的對象
     第二個參數(shù): 回調(diào)block的隊(duì)列, 決定了block在哪個線程中執(zhí)行
     第三個參數(shù): 回調(diào)block
     */
    // 注意點(diǎn): 如果是調(diào)用NSURLConnection的同步方法, 會阻塞當(dāng)前線程
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        /*
         response: 響應(yīng)頭
         data : 響應(yīng)體
         connectionError : 錯誤信息
         */
        //        NSLog(@"%@", [NSThread currentThread]);
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
  • POST請求:
    // 1.創(chuàng)建一個URL
    NSURL *url = [NSURL URLWithString:@"http://admin/login"];
    // 2.根據(jù)URL創(chuàng)建NSURLRequest對象
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    /*
     NSMutableURLRequest中保存了請求的地址/請求頭/請求體
     */
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 2.1設(shè)置請求方式
    // 注意: POST一定要大寫
    request.HTTPMethod = @"POST";
    // 2.2設(shè)置請求體
    // 注意: 如果是給POST請求傳遞參數(shù): 那么不需要寫?號
    request.HTTPBody = [@"username=Mitchell&pwd=123456&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    
    // 3.利用NSURLConnection對象發(fā)送請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
  • NSURLConnection 與 NSRunLoop 的關(guān)聯(lián)使用
    • 主要是區(qū)分 NSURLConnection 在主線程和子線程發(fā)送網(wǎng)絡(luò)請求的區(qū)別
    • 主線程
      • 1、 直接發(fā)送網(wǎng)絡(luò)請求,發(fā)送是異步的,但是代理方法是在主線程中執(zhí)行的:
    NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
    NSURLRequest*request = [NSURLRequest requestWithURL:url];
    //這里分兩種方式發(fā)送請求
    //2.1 直接發(fā)送網(wǎng)絡(luò)請求是異步的,但是回調(diào)方法是在主線程中執(zhí)行的
    //[[NSURLConnection alloc]initWithRequest:request delegate:self];
    * 2、如果按照如下設(shè)置,那么回調(diào)的代理方法也會運(yùn)行在子線程中:
NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
    NSURLRequest*request = [NSURLRequest requestWithURL:url];
    //2.2 設(shè)置回調(diào)方法也在子線程中運(yùn)行
    NSURLConnection*conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
    [conn setDelegateQueue:[[NSOperationQueue alloc] init]];
    [conn start];
- 子線程
    * `因?yàn)?NSURLConnection 是局部變量`,當(dāng)我們創(chuàng)建的時候其實(shí)是會默認(rèn)`添加到當(dāng)前的 RunLoop 中`,如果是在主線程添加,主線程的 RunLoop 是默認(rèn)有的,無須我們創(chuàng)建,`然而如果再子線程中,是默認(rèn)沒有 RunLoop 和輸入源的,所以需要給子線程手動添加 RunLoop` 。
    * 為什么使用 `start` 方法就可以呢?

因?yàn)?start 方法如果沒有 RunLoop ,會默認(rèn)添加一個 RunLoop 到當(dāng)前的線程中來。

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
        NSURLRequest*request = [NSURLRequest requestWithURL:url];
        
        //2.1 這么設(shè)置還是可以的
//NSURLConnection*conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
//[conn start];
        
        //2.2 但是這樣設(shè)置就不行了
//[NSURLConnection connectionWithRequest:request delegate:self];
        /*問題一:為什么?
         NSURLConnection 是臨時變量,當(dāng)運(yùn)行的時候被默認(rèn)添加到當(dāng)前線程的 RunLoop 中,由于主線程的RunLoop是默認(rèn)存在的,所以可以運(yùn)行,這里不行能的原因就是當(dāng)前線程并沒有 RunLoop,如果想讓其運(yùn)行,比需要創(chuàng)建RunLoop。
         問題二:為什么2.1就可以?
         因?yàn)閟tart方法:如果沒有一個runloop,它會自動給當(dāng)前線程添加runLoop,然后將connection加到runLoop中。
         If you don’t schedule the connection in a run loop or an operation queue before calling this method, the connection is scheduled in the current run loop in the default mode.
         */
        //2.2解決方式
       NSRunLoop*loop =  [NSRunLoop currentRunLoop];
        [NSURLConnection connectionWithRequest:request delegate:self];
        [loop run];
    });

二、NSURLSession

  • 推薦使用
  • 簡單使用
    • Get
    //注意:如果需要改請求頭 需要使用這種方法
    NSURL*url = [NSURL URLWithString:@"httpAddress"];
    NSURLRequest*request = [NSURLRequest requestWithURL:url];
    //1、創(chuàng)建NSURLSession
    NSURLSession*session = [NSURLSession sharedSession];
    //2、利用NSURLSession創(chuàng)建Tash
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        /*
         data:服務(wù)器返回高i的數(shù)據(jù)
         response:響應(yīng)頭
         error:錯誤信息
         */
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    //3、執(zhí)行Task
    [task resume];
    * 
    NSURL*url = [NSURL URLWithString:@"httpAddress"];
    //1、創(chuàng)建NSURLSession
    NSURLSession*session = [NSURLSession sharedSession];
    //2、利用NSURLSession創(chuàng)建Tash
    // 如果是通過url的方法創(chuàng)建Task,方法內(nèi)部會自動根據(jù)URL創(chuàng)建一個request
    // 如果是發(fā)送Get請求,或者不需要設(shè)置請求頭信息,那么建議使用當(dāng)前方法發(fā)送請求
    NSURLSessionDataTask*task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    //3、執(zhí)行Task
    [task resume];
- POST
    NSURL*url = [NSURL URLWithString:@"httpAddress"];
    NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody =@"需要發(fā)送的信息";
    //1、創(chuàng)建NSURLSession
    NSURLSession*session = [NSURLSession sharedSession];
    //2、利用NSURLSession創(chuàng)建Tash
    NSURLSessionDataTask*task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    //3、執(zhí)行Task
    [task resume];
  • 斷點(diǎn)下載
#import "ViewController.h"
#import "NSString+Mitchell.h"
@interface ViewController () <NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *pro;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (nonatomic,strong) NSURLSession             * session;
@property(nonatomic,assign)CGFloat totalLength;
@property(nonatomic,assign)CGFloat currentLength;
@property(nonatomic,strong)NSURLSessionDataTask*task;
@property(nonatomic,strong)NSOutputStream * stream;
@property(nonatomic,strong)NSString * path;
@end
@implementation ViewController
  - (void)viewDidLoad {
    [super viewDidLoad];
    //初始化操作
    //1、初始化文件路徑
    self.path = [@"abc.mp4" cacheDir];
    //2、初始化當(dāng)前下載進(jìn)度
    self.currentLength = [self getFileSizeWithPath:self.path];
 }
 #pragma mark ------------------ delegate ------------------
 //注意:NSURLSessionDataTask的代理方法中,默認(rèn)情況下是不接受服務(wù)器返回的數(shù)據(jù)的,所以didCompleteWithError、didReceiveData默認(rèn)不會被調(diào)用
 //如果想接受服務(wù)器返回的數(shù)據(jù),必須手動告訴系統(tǒng),我們需要接受數(shù)據(jù)
  - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    NSLog(@"didReceiveResponse");
    self.totalLength = response.expectedContentLength;
    //告訴服務(wù)器接受,才能調(diào)用didCompleteWithError、didReceiveData兩個方法
    NSString*path = [@"abc.mp4" cacheDir];
    NSLog(@"%@",path);
    _stream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
    [_stream open];
    completionHandler(NSURLSessionResponseAllow);
}
  -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    self.currentLength +=data.length;
    self.pro.progress = 1.0*_currentLength/_totalLength;
    [_stream write:data.bytes maxLength:data.length];
    NSLog(@"didReceiveData");
}
  -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    NSLog(@"didCompleteWithError");
    [_stream close];
    _stream = nil;
}
  - (NSURLSession *)session{
    if (!_session) {
        //1、創(chuàng)建NSURLSession
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}
  - (NSURLSessionDataTask *)task{
    if (!_task) {
        //圖片:http://img1.imgtn.bdimg.com/it/u=298400068,822827541&fm=21&gp=0.jpg%2F2008-09-08%2F200898163242920_2.jpg&bdtype=0&fr=ala&ala=1&alatpl=others&pos=1
        //MP4:http://mvvideo1.meitudata.com/55d99e5939342913.mp4
        NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
        NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:url];
        NSString*range = [NSString stringWithFormat:@"bytes:%zd-",[self getFileSizeWithPath:self.path]];
        [request setValue:range forHTTPHeaderField:@"Range"];
        //2、利用NSURLSession創(chuàng)建Tash
        _task = [self.session dataTaskWithURL:url];
    }
    return _task;
}
  - (NSUInteger)getFileSizeWithPath:(NSString*)path{
    NSUInteger currentSize = [[[NSFileManager defaultManager]attributesOfItemAtPath:path error:nil][NSFileSize] integerValue];
    return currentSize;
}
 #pragma mark ------------------ 開始 ------------------
  - (IBAction)start:(id)sender {
    //3、執(zhí)行Task
    [self.task resume];

}
 #pragma mark ------------------ 暫停 ------------------
  - (IBAction)pause:(id)sender {
    NSLog(@"暫停");
    [self.task suspend];
}
 #pragma mark ------------------ 繼續(xù) ------------------
  - (IBAction)resume:(id)sender {
    NSLog(@"繼續(xù)");
    [self.task resume];
}
 #pragma mark ------------------ 取消 ------------------
  - (IBAction)cancel:(id)sender {
}
@end
  • 下載進(jìn)度
#import "ViewController.h"
#import "NSString+Mitchell.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (weak, nonatomic ) IBOutlet UIProgressView           *pro;
@property (weak, nonatomic ) IBOutlet UIButton                 *startBtn;
@property (weak, nonatomic ) IBOutlet UIButton                 *cancelBtn;
@property (nonatomic,strong) NSURLSessionDownloadTask * task;
@property (nonatomic,strong) NSData                   * resumeData;
@property (nonatomic,strong) NSURLSession             * session;
@end
@implementation ViewController
   - (void)viewDidLoad {
    [super viewDidLoad];
}
#pragma mark ------------------ didFinishDownloadingToURL ------------------
//下載完成時調(diào)用
 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    NSString*toPath = [@"abc.mp4" cacheDir];
    NSURL*toUrl = [NSURL fileURLWithPath:toPath];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager moveItemAtURL:location toURL:toUrl error:nil];
    NSLog(@"%@",toUrl);
    NSLog(@"didFinishDownloadingToURL");
    _startBtn.userInteractionEnabled = YES;
}
#pragma mark ------------------ didWriteData ------------------
//接收服務(wù)器返回的數(shù)據(jù)時調(diào)用
 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //bytesWritten:每次接收了多少
    //totalBytesWritten:本地寫入了多少
    //totalBytesExpectedToWrite:一共多少
NSLog(@"%zd,%zd,%zd",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    self.pro.progress = 1.0* totalBytesWritten/totalBytesExpectedToWrite;
}
#pragma mark ------------------ didResumeAtOffset ------------------
//恢復(fù)下載時候調(diào)用(使用resumeData恢復(fù)下載的時候才能調(diào)用)
 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
    NSLog(@"didResumeAtOffset");
}
//下載完成時調(diào)用
//如果下載時候error有值,代表著下載出錯
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    NSLog(@"didCompleteWithError");
    _startBtn.userInteractionEnabled = YES;
}
#pragma mark ------------------ 開始 ------------------
 - (IBAction)start:(id)sender {
    //圖片:http://img1.imgtn.bdimg.com/it/u=298400068,822827541&fm=21&gp=0.jpg%2F2008-09-08%2F200898163242920_2.jpg&bdtype=0&fr=ala&ala=1&alatpl=others&pos=1
    //MP4:http://mvvideo1.meitudata.com/55d99e5939342913.mp4
    NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
    NSURLRequest*request = [NSURLRequest requestWithURL:url];
    //1、創(chuàng)建NSURLSession
    /*
     第一個參數(shù):Session的配置信息
     第二個參數(shù):代理
     第三個參數(shù):規(guī)定了代理方法在哪個線程中執(zhí)行
     */
    _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //2、利用NSURLSession創(chuàng)建Task
    _task = [self.session downloadTaskWithRequest:request];
    //3、執(zhí)行Task
    [_task resume];
    _startBtn.userInteractionEnabled = NO;
}
#pragma mark ------------------ 暫停 ------------------
 - (IBAction)pause:(id)sender {
    NSLog(@"暫停");
    [_task suspend];
}
#pragma mark ------------------ 繼續(xù) ------------------
  - (IBAction)resume:(id)sender {
    NSLog(@"繼續(xù)");
//    [_task resume];
    //恢復(fù)信息恢復(fù)下載,用獲取到resumeData繼續(xù)下載
    self.task = [_session downloadTaskWithResumeData:_resumeData];
    [self.task resume];
}
#pragma mark ------------------ 取消 ------------------
 - (IBAction)cancel:(id)sender {
    //取消
    //注意點(diǎn):一旦取消,就不能恢復(fù)了
//    [_task cancel];
    //如果是調(diào)用了cancelByProducingResumeData方法,方法內(nèi)部會回調(diào)一個block,在block中會將resumeData傳遞給我們
    //resumeData中就保存了當(dāng)前下載任務(wù)的配置信息(下載到什么地方,從什么地方恢復(fù)等等)
    [self.task cancelByProducingResumeData:^(NSData *resumeData) {
        self.resumeData = resumeData;
    }];
}
@end
  • 上傳
#import "ViewController.h"
// 請求頭的
#define MitchellHeaderBoundary @"----xiaomage"
// 請求體的
#define MitchellBoundary [@"------xiaomage" dataUsingEncoding:NSUTF8StringEncoding]
// 結(jié)束符
#define MitchellEndBoundary [@"------xiaomage--" dataUsingEncoding:NSUTF8StringEncoding]
// 將字符串轉(zhuǎn)換為二進(jìn)制
#define MitchellEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
// 換行
#define MitchellNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
@interface ViewController ()<NSURLSessionTaskDelegate>
@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{
    NSURL*url = [NSURL URLWithString:@""];
    NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:url];    
    //1、創(chuàng)建Session
    NSURLSession*session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //2、根據(jù)Seesion創(chuàng)建Task
    /*
    //注意:fromFile方法是用于PUT請求上傳文件的
    //而我們的服務(wù)器只支持POST請求上傳文件
    NSURL*fileUrl = [NSURL fileURLWithPath:@""];
    NSURLSessionUploadTask*task = [session uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    }];
     */
    /*請求體
     第一個參數(shù):需要請求的地址/請求頭/
     第二個參數(shù):需要上傳拼接之后的二進(jìn)制數(shù)據(jù)
     */
    request.HTTPMethod = @"POST";
//    NSURL*fileUrl = [NSURL fileURLWithPath:@""];
//    NSData*data =[NSData dataWithContentsOfURL:fileUrl];
    // 2.2設(shè)置請求體
    NSMutableData *data = [NSMutableData data];
    // 2.2.1設(shè)置文件參數(shù)
    [data appendData:MitchellBoundary];
    [data appendData:MitchellNewLine];
    // name : 對應(yīng)服務(wù)端接收的字段類型(服務(wù)端參數(shù)的名稱)
    // filename: 告訴服務(wù)端當(dāng)前的文件的文件名稱(也就是告訴服務(wù)器用什么名稱保存當(dāng)前上傳的文件)
    [data appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"videos.plist\"" dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:MitchellNewLine];
    [data appendData:[@"Content-Type: application/octet-stream" dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:MitchellNewLine];
    [data appendData:MitchellNewLine];
    //上傳文件的數(shù)據(jù)
    NSURL*fileUrl = [NSURL fileURLWithPath:@""];
    NSData*imgData = [NSData dataWithContentsOfURL:fileUrl];    
    [data appendData:imgData];
    [data appendData:MitchellNewLine];
    [data appendData:MitchellNewLine];
    // 2.2.2設(shè)置非文件參數(shù)
    [data appendData:MitchellBoundary];
    [data appendData:MitchellNewLine];
    // name : 對應(yīng)服務(wù)端接收的字段類型(服務(wù)端參數(shù)的名稱)
    [data appendData:[@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:MitchellNewLine];
    [data appendData:MitchellNewLine];
    [data appendData:[@"Mitchell" dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:MitchellNewLine];
    // 2.2.3設(shè)置結(jié)束符號
    [data appendData:MitchellEndBoundary];
     //注意點(diǎn):如果利用NSURLSessionUploadTask上傳文件,那么請求體必須卸載fromData參數(shù)中,不能設(shè)置在request中
    //如果設(shè)置在request中會被忽略
    //
    request.HTTPBody = data;
    NSURLSessionUploadTask*task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    }];
    //3、執(zhí)行Task
    [task resume];   
}
#pragma mark ------------------ Delegate ------------------
//上傳過程中調(diào)用
//bytesSent:當(dāng)前這一次上傳的數(shù)據(jù)大小
//totalBytesSent:總共已經(jīng)上傳的數(shù)據(jù)大小
//totalBytesExpectedToSend:需要上傳文件的大小
 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
NSLog(@"%f",1.0*totalBytesSent/totalBytesExpectedToSend);
}
//請求完畢時調(diào)用
 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    //用block方式 創(chuàng)建是不會調(diào)用這個方法
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容