Session會話

weixin_34290000發表於2017-09-08

/*
 
 NSURLSession用來替代NSURLConnection。
 
 他相比NSURLConnection 更靈活,更好用。
 
 NSURLSessionUploadTask 繼承自 NSURLSessionDataTask 繼承自
 NSURLSessionTask
 
 NSURLSessionDownloadTask 繼承自 NSURLSessionTask
 
 NSURLSessionDataTask任務預設是掛起狀態,使用之前執行resume
 
 */

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self get];
    [self post];
    [self download];
}


#pragma mark - GET請求
- (void)get
{
    //get
    NSString * urlString = @"http://192.168.20.11/login.php";
    
    //建立一個會話類
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?username=ios&password=123",urlString]];
    
    //Request開啟一個任務:
    NSURLSessionDataTask * task1 = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    //直接通過Url開啟一個任務:
    NSURLSessionDataTask * task2 = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    //執行任務:
    [task1 resume];
    [task2 resume];
    
}


#pragma mark - POST請求
- (void)post
{
    //一個POST請求:
    NSURL *url = [NSURL URLWithString:@"http://192.168.20.11/login.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //設定請求方法為POST , 預設為GET請求 , 必須使用可變的網路請求類 NSMutableURLRequest 否則 HTTPMethod 是隻讀屬性!
    request.HTTPMethod = @"POST";
    //設定請求體 , get請求和post請求的一個區別就是配置放入請求體裡和追加在url後面用?分隔:
    request.HTTPBody = [@"username=ios&password=123" dataUsingEncoding:NSUTF8StringEncoding];
    //獲取全域性網路會話物件:
    NSURLSession *session = [NSURLSession sharedSession];
    
    //通過Request獲取網路資料並執行網路請求:
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"%@" , [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    }] resume];

    //通過Url獲取網路資料並執行網路請求:
    [[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"%@" , [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        
    }] resume];
    
}


#pragma mark - 下載任務請求
- (void)download
{
    // stringByAddingPercentEscapesUsingEncoding: 被stringByAddingPercentEncodingWithAllowedCharacters:方法替代:裡面傳的是一個 集合類 NSCharacterSet;
    // URLQueryAllowedCharacterSet:返回包含URL查詢元件中允許的字元的字符集。
    //解決介面中有中文欄位的問題:
    NSString * string = [@"http://192.168.20.11/程式設計師之歌.mp3" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL * url = [NSURL URLWithString:string];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //Url直接下載:
    [[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //當前臨時檔案的地址
        NSLog(@"location - %@",location);
        
        //獲取快取檔案目錄: suggestedFilename 響應頭回傳的檔名:
        NSString * cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        
        //獲取快取檔案網路地址:
        NSURL * toUrl = [NSURL fileURLWithPath:cachePath];
        NSFileManager * mgr = [NSFileManager defaultManager];
        
        NSError * error2 = nil;
        //將臨時檔案移動到快取檔案目錄中:
        [mgr moveItemAtURL:location toURL:toUrl error:&error2];
        
    }] resume];
    
    
    //Request下載:
    [[[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //當前檔案所儲存的臨時地址:
        NSLog(@"%@" , location);
        
        NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSURL *toUrl = [NSURL fileURLWithPath:cachePath];
        NSError *pathError = nil;
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:toUrl error:&pathError];
        
    }] resume];
    
}

@end

願程式設計讓這個世界更美好

相關文章