您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 網路學習(1):GET 與 POST 非同步請求實作

編輯:iOS 開發綜合

發網路請求的基本三步驟是:建立 NSURL、建立 NSURLRequest、建立並啟動 NSURLConnection。GET 與 POST 的差別只在第二步與資料承載方式。

一、GET 請求

- (void)loginWithGet:(NSString *)name pwd:(NSString *)pwd {
    // 1. 確定網址,參數直接接在 query string 後面
    NSString *urlString = [NSString stringWithFormat:
        @"https://www.baidu.com?username=%@&password=%@", name, pwd];

    // URL 中含中文時必須轉為百分號編碼,供伺服器解碼
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];

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

    // 3. 建立並啟動連線(非同步)
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];

    // 準備中轉用的緩衝資料
    self.serverData = [NSMutableData data];
}

這裡的 stringByAddingPercentEscapesUsingEncoding 是必要的。URL 只允許 ASCII 字元,中文若不編碼,NSURL 會直接回傳 nil,連請求都發不出去。

二、POST 請求

- (void)login {
    NSString *userName = self.nameTextField.text;
    NSString *pwd = self.passwordTextField.text;

    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];

    // POST 必須用「可變」請求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 1) 明確宣告請求方式,預設是 GET
    [request setHTTPMethod:@"POST"];

    // 2) 設定請求本文。dataUsingEncoding 已完成編碼,中文不必另外處理
    NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@", userName, pwd];
    NSData *body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:body];

    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];

    self.serverData = [NSMutableData data];
}

兩個重點:一是 POST 必須用 NSMutableURLRequest,因為要改 method 與 body;二是 POST 的本文中文字不需手動編碼,dataUsingEncoding 已處理。

三、五個 delegate 方法

// 1. 收到回應:伺服器要開始傳了,客戶端做好接收準備
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}

// 2. 收到資料:可能呼叫多次,必須拼接
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.serverData appendData:data];
}

// 3. 完成:對拼接後的資料做後續處理
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *str = [[NSString alloc] initWithData:self.serverData
                                          encoding:NSUTF8StringEncoding];

    NSRange range = [str rangeOfString:@"用戶名"];
    NSString *msg = nil;

    if (range.location > 0) {
        NSString *name = [str substringFromIndex:(range.location + range.length)];
        msg = [NSString stringWithFormat:@"歡迎回來:%@", name];
    } else {
        msg = @"用戶名或者密碼錯誤,請重試!";
    }

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"確定"
                                          otherButtonTitles:nil];
    [alert show];

    self.serverData = nil; // 清掉緩衝
}

// 4. 失敗:網路環境、DNS、逾時等原因都可能
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"網絡連接請求錯誤 %@", error.localizedDescription);
}

// 5. 上傳進度回報(POST 上傳時有用)
- (void)connection:(NSURLConnection *)connection
   didSendBodyData:(NSInteger)bytesWritten
 totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    NSLog(@"已送出 %ld / 共 %ld", (long)totalBytesWritten, (long)totalBytesExpectedToWrite);
}

四、幾個觀念釐清

為什麼要用 appendData 拼接?因為 TCP 是串流協定,伺服器送來的內容會被切成多個封包,didReceiveData 會被呼叫多次。若不拼接,你拿到的永遠只是最後一塊碎片。這也是為什麼要先實作 didReceiveResponse 宣告一個空的 NSMutableData 容器。

didSendBodyData 的用途。四個參數分別是本次送出量、累計送出量、預期總量。上傳檔案時可以用它計算百分比並更新進度條。GET 請求不會觸發這個方法。

為什麼要在方法中避免直接存取屬性。像 serverData 這種與介面狀態無關的中轉資料,用參數傳遞會比全域屬性清楚,也較不易在多次請求並行時互相干擾。

最後務實提醒:NSURLConnection 在 iOS 9 已被標記為 deprecated,且預設不允許明文 HTTP(ATS 限制)。新專案請改用 NSURLSession:

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task =
    [session dataTaskWithRequest:request
               completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // 拼接與錯誤處理都由你掌控,記得切回主線程更新 UI
    }];
[task resume];

其中的 data 已是完整資料,不必再自己拼接,錯誤也統一從 completionHandler 的 error 參數取得,比五個 delegate 方法直觀得多。

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