您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 網路基礎:NSURLRequest 與 NSURLConnection 詳解

編輯:iOS 相關資訊

NSURLRequest:封裝一次請求

NSURLRequest 負責把「要怎麼請」這件事打包成一個物件,內容包含:

  • 請求路徑(URL)
  • 請求方法(GET 或 POST)
  • 請求標頭
  • 請求本文
  • 逾時參數

它與其子類 NSMutableURLRequest 的關鍵差異在於可變性:NSURLRequest 建立後不可修改,且所有資訊都拼在 URL 後面;NSMutableURLRequest 則把路徑與其他資訊分開,可以逐一透過對應的屬性設定,因此通常用於 POST 請求。實務上的分工大致是:NSURLRequest 用於 GET,NSMutableURLRequest 用於 POST。

建立 GET 請求

// 1. 拼接請求路徑,參數直接接在 URL 後
NSString *strURL = [NSString stringWithFormat:@"(此處為 URL)/login?username=%@&pwd=%@",
                    @"用戶名", @"密碼"];
NSURL *url = [NSURL URLWithString:strURL];

// 2. 封裝成請求物件
NSURLRequest *request = [NSURLRequest requestWithURL:url];

建立 POST 請求

// 1. 請求路徑不含參數
NSURL *url = [NSURL URLWithString:@"(此處為 URL)/login"];

// 2. 建立可變請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 3. 指定方法
request.HTTPMethod = @"POST";

// 4. 把參數放進請求本文
request.HTTPBody = [@"username=用戶名&pwd=密碼" dataUsingEncoding:NSUTF8StringEncoding];

// 5. 設定逾時秒數
request.timeoutInterval = 5;

順帶一提,GET 請求把帳密放在 URL 上會被伺服器日誌完整記錄,屬於不良實務。任何敏感資訊都應走 POST 並搭配 HTTPS。

NSURLConnection 的三個步驟

  1. 建立請求路徑(NSURL)
  2. 封裝成請求物件(NSURLRequest),設定其他參數
  3. 以 NSURLConnection 送出同步或異步請求

相關 delegate 協議

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
// 遇到錯誤,請求終止

NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
// 收到回應,response 中最有價值的是本次資料的總長度

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
// 收到資料;資料量大時會多次呼叫
// 可在此保存資料,或計算下載進度

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
// 資料載入完畢

NSURLConnectionDownloadDelegate

- (void)connection:(NSURLConnection *)connection
      didWriteData:(long long)bytesWritten
 totalBytesWritten:(long long)totalBytesWritten
expectedTotalBytes:(long long)expectedTotalBytes
// 每次向沙盒寫檔都會呼叫

- (void)connectionDidResumeDownloading:(NSURLConnection *)connection
                   totalBytesWritten:(long long)totalBytesWritten
           expectedTotalBytes:(long long)expectedTotalBytes
// 支援斷點續傳的核心方法

- (void)connectionDidFinishDownloading:(NSURLConnection *)connection
                       destinationURL:(NSURL *)destinationURL
// 檔案位於 tmp,該目錄會被系統週期性清理
// 因此必須實作此方法,把檔案移到長期保存的位置

同步請求

會阻塞目前執行緒,在主執行緒呼叫會直接讓 UI 凍結,只適合在背景隊列中使用。

NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                    returningResponse:&response
                                                error:&error];
// data:伺服器回傳的內容
// response:回應中繼資料
// error:錯誤資訊

異步請求

// 方法一:Block 回呼
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[[NSOperationQueue alloc] init]
                         completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    // 參數含義與同步版本相同
}];

// 方法二:delegate,會自動送出請求
[NSURLConnection connectionWithRequest:request delegate:self];

// 若要手動控制送出時機,startImmediately 傳 NO
NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:request
                                                        delegate:self
                                                startImmediately:NO];

URL 中的中文處理

URL 只允許 ASCII 字元,中文必須先做百分比編碼,一般使用 UTF-8:

[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

實務上要留意,這個方法不會編碼 &、?、= 等保留字元。若你的參數值本身含有這些字元,改用 NSURLComponents 的 queryItems 讓系統代為處理會安全得多。

最後必須說明:NSURLConnection 自 iOS 9 起已被蘋果標記為 deprecated,新專案請一律改用 NSURLSession。理解 NSURLConnection 的 delegate 模型仍有價值,因為 NSURLSession 的設計思路完整承襲了它,只是把「連線」抽象成了「任務」。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved