IOS 網路淺析-(八 NSURLSession簡介),iosnsurlsession

來源:互聯網
上載者:User

IOS 網路淺析-(八 NSURLSession簡介),iosnsurlsession

就在不長也不短的時間前,蘋果正式命令咱們要向NSURLSession看,因此我們不得不認認真真的聽從老大的教導,努力認知NSURLSession。其實呢,三方早已為我們解決了問題,但是呢,我們還是有必要大概瞭解一下NSURLSession。下面呢,我就為大家簡單介紹NSURLSession。

*下面是一位大牛寫過的一段話,在此獻上* 

NSURLConnection在開發中會使用的越來越少,iOS9已經將NSURLConnection廢棄,現在最低版本一般適配iOS,所以也可以使用。NSURLConnection上傳圖片,可以自己找資料。

NSURLConnection相對於NSURLSession,安全性低。NSURLConnection下載有峰值,比較麻煩處理。

儘管適配最低版本iOS7,也可以使用NSURLSession。AFN已經不支援NSURLConnection。

NSURLSession:會話。預設是掛起狀態,如果要請求網路,需要開啟。

[NSURLSession sharedSession] 擷取全域的NSURLSession對象。在iPhone的所有app共用一個全域session.

NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask

NSURLSessionDownloadTask -> NSURLSessionTask

NSURLSessionDownloadTask下載,預設下載到tmp檔案夾。下載完成後刪除臨時檔案。所以我們要在刪除檔案之前,將它移動到Cache裡。

下載 測試

////  ViewController.m//  CX-NSURLSession簡介////  Created by ma c on 16/3/21.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    }//這是為了測試而建立的點擊螢幕事件。-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{        //下載 測試        NSURL * url = [NSURL URLWithString:[@"http://localhost/tupian.jpg" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];        NSURLRequest * request = [NSURLRequest requestWithURL:url];        NSURLSession * session = [NSURLSession sharedSession];        NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {               NSLog(@"下載完成");        //response.suggestedFilename 響應資訊中的資源檔名        NSString * cacheParh = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingString:response.suggestedFilename];        NSLog(@"緩衝地址%@",cacheParh);        //擷取檔案管理工具        NSFileManager * manager = [NSFileManager defaultManager];                //將臨時檔案移動到緩衝目錄下        //[NSURL fileURLWithPath:cachesPath] 將本地路徑轉化為URL類型        //URL如果地址不正確,產生的url對象為空白                [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:cacheParh] error:NULL];    }];        //開啟任務    [task resume];}@end

 

GET 測試 一

////  ViewController.m//  CX-NSURLSession簡介////  Created by ma c on 16/3/21.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    }//這是為了測試而建立的點擊螢幕事件。-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{        //get測試一        //建立URL    NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"];    //建立 NSURLSession    NSURLSession * session = [NSURLSession sharedSession];        //建立任務    NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {               NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);            }];    //開啟任務    [task resume];        }@end

GET 測試 二 

////  ViewController.m//  CX-NSURLSession簡介////  Created by ma c on 16/3/21.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    }//這是為了測試而建立的點擊螢幕事件。-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{        //get測試二        //建立URL    NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"];    //建立請求    NSURLRequest * request = [NSURLRequest requestWithURL:url];    //建立 NSURLSession    NSURLSession * session = [NSURLSession sharedSession];        //建立任務        NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {               NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);    }];    //開啟任務    [task resume];        }@end

POST 測試

////  ViewController.m//  CX-NSURLSession簡介////  Created by ma c on 16/3/21.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    }//這是為了測試而建立的點擊螢幕事件。-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{        //post 測試        //建立URL    NSURL * url = [NSURL URLWithString:@"http://localhost/login.php"];    //建立請求    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];        request.HTTPMethod = @"POST";        request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding];        //建立 NSURLSession    NSURLSession * session = [NSURLSession sharedSession];        //建立任務        NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {               NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);    }];    //開啟任務    [task resume];        }@end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.