NSURLSession 簡介

步驟:
(1) 得到 session 對象, NSURLSession *session = [NSURLSession sharedSession];
(2) 創建一個task, 任何一個請求都是一個任務

NSURLSessionDataTask // 普通任務
NSURLSessionDownLoadTask // 文件下載任務
NSURLSessionUploadTask // 文件上傳任務

NSURLSession 實現 GET 請求

- (IBAction)login {
    //判斷賬號與密碼是否爲空
    NSString *name = _accountText.text;
    if (name == nil || name.length == 0){
        NSLog(@"請輸入賬號");
        return;
    }

    NSString *pwd = _pwdText.text;
    if (pwd == nil || pwd.length == 0){
        NSLog(@"請輸入密碼");
        return;
    }

    //創建URL
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/Server/login?username=%@&pwd=%@", name, pwd];

    //用NSURLSession實現登錄
    [self sessionWithUrl:urlStr];
}

- (void)sessionWithUrl:(NSString *)urlStr{
    NSURL *url = [NSURL URLWithString:urlStr];

    //用NSURLConnection實現登錄
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil || error != nil) {
            NSLog(@"請求失敗");
            return;
        }

        //JSON解析
        NSError *error2;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error2];
        if (error2) {
            NSLog(@"解析失敗 -- %@", error2);
        }
        NSLog(@"數據爲 -- %@", dict);
    }];
    [task resume];

}

NSURLSession 實現 POST 請求:

- (IBAction)login {
    //判斷賬號與密碼是否爲空
    NSString *name = _accountText.text;
    if (name == nil || name.length == 0){
        NSLog(@"請輸入賬號");
        return;
    }

    NSString *pwd = _pwdText.text;
    if (pwd == nil || pwd.length == 0){
        NSLog(@"請輸入密碼");
        return;
    }


    //用NSURLSession實現登錄
    //創建URL
    NSString *urlStr = @"http://localhost:8080/Server/login";
    [self sessionWithUrl:urlStr];
}

- (void)sessionWithUrl:(NSString *)urlStr{
    NSURL *url = [NSURL URLWithString:urlStr];

    //用NSURLConnection實現登錄
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //POST請求
    request.HTTPMethod = @"POST";
    NSString *prama = [NSString stringWithFormat:@"username=%@&pwd=%@", _accountText.text, _pwdText.text];
    //中文轉碼
    [prama stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //轉碼
    request.HTTPBody = [prama dataUsingEncoding:NSUTF8StringEncoding];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil || error != nil) {
            NSLog(@"請求失敗");
            return;
        }

        //JSON解析
        NSError *error2;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error2];
        if (error2) {
            NSLog(@"解析失敗 -- %@", error2);
        }
        NSLog(@"數據爲 -- %@", dict);
    }];
    [task resume];

}

NSURLSession 實現 斷點續傳:

//斷點下載
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

//懶加載
- (NSURLSession *)session{
    if (!_session) {
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

/**
 *  NSURLSession實現斷點下載
 */
- (IBAction)startDowbLoad:(id)sender {
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos/minion_01.mp4"];
    self.task = [self.session downloadTaskWithURL:url];
    //開始下載
    [self.task resume];
}

/**
 *  暫停下載
 */
- (IBAction)pauseDownLoad:(id)sender{
    __weak typeof (self) vc = self;
    /**
     *  @param resumeData 包含了繼續下載開始的位置和下載的URL
     */
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        vc.resumeData = resumeData;
        self.task = nil;
    }];
}

/**
 *  恢復下載
 */
- (IBAction)resumeDownLoad:(id)sender {
    //傳入上次下載的數據
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    //開始下載
    [self.task resume];
    //清空
    self.resumeData = nil;
}

#pragma mark - NSURLSessionDelegate 代理方法
//下載完成調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //下載完成後,寫入 caches 文件中
    NSString *cachesFile = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtPath:location.path toPath:cachesFile error:nil];
}

/**
 *  下載過程中調用這個方法, 每當下載完(寫完)一部分時會調用, (可能被調用多次)
 *
 *  @param bytesWritten              這次寫了多少
 *  @param totalBytesWritten         累計寫了多少
 *  @param totalBytesExpectedToWrite 文件的總長度
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
}

//恢復下載的時候調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章