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

iOS 網路請求四種寫法:GET/POST 的同步、非同步與 block

編輯:iOS 開發綜合

這份筆記整理 NSURLConnection 時代的四種常見請求方式:GET 同步、POST 同步、GET 非同步(delegate)、POST 非同步與 block 寫法。雖然 NSURLConnection 已被廢棄,但理解這些底層流程,對之後學 NSURLSession 很有幫助。

ViewController 的結構

#import "ViewController.h"

@interface ViewController () <NSURLConnectionDataDelegate>

- (IBAction)synGET:(id)sender;
- (IBAction)synPOST:(id)sender;
- (IBAction)asynGET:(id)sender;
- (IBAction)asynPOST:(id)sender;
- (IBAction)block:(id)sender;

@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) NSMutableData *data;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(200, 100, 150, 150)];
    self.imageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.imageView];
    [_imageView release];
}

一、GET 同步請求

- (IBAction)synGET:(id)sender {
    NSString *strURL = @"https://api.map.baidu.com/place/v2/search?query=銀行&region=大連&output=json&ak=XXXX";

    // 正常的 URL 不允許中文,只能有英文字母、數字與少數特殊符號(如 &、%)。
    // 遇到含中文的 URL,必須先做編碼
    NSString *strEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // 網路請求分三步
    // 1. 由編碼後的 URL 建立 NSURL
    NSURL *url = [NSURL URLWithString:strEncode];

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

    // 3. 取得資料。三個參數分別是請求、回應、錯誤
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                        returningResponse:&response
                                                    error:&error];

    // JSON 解析,把銀行名稱印出來
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                              options:NSJSONReadingMutableContainers
                                                                error:nil];
    NSMutableArray *arr = dic[@"results"];
    for (NSDictionary *dic in arr) {
        NSLog(@"%@", dic[@"name"]);
    }
}

二、POST 同步請求

- (IBAction)synPOST:(id)sender {
    NSString *strURL = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // POST 特有的部分
    // 1. 把請求方式設為 POST(預設是 GET)
    [request setHTTPMethod:@"POST"];

    // 2. 把參數放進 request 的 body
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];

    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                        returningResponse:nil
                                                    error:nil];

    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                              options:NSJSONReadingMutableContainers
                                                                error:nil];
    NSLog(@"%@", dic);
}

三、GET 非同步請求(delegate 方式)

- (IBAction)asynGET:(id)sender {
    NSString *strURL = @"https://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 前兩步與同步相同,第三步改為透過 delegate 進行非同步操作
    [NSURLConnection connectionWithRequest:request delegate:self];
}

接著實作三個 delegate 方法:

// 收到回應時呼叫,在這裡初始化資料容器
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
    self.data = [NSMutableData data];
}

// 每次收到部分資料都會呼叫,用 append 累加
- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data {
    [self.data appendData:data];
}

// 整個請求結束,把資料指定給 imageView
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.imageView.image = [UIImage imageWithData:self.data];
}

這裡有個關鍵點:GET 的同步與非同步在步驟上完全相同,差別只在第三步——同步用 sendSynchronousRequest:,非同步用 connectionWithRequest:delegate: 並實作回呼。非同步是建立在同步的流程概念之上,只是把「等待」交給 run loop。

四、POST 非同步請求

- (IBAction)asynPOST:(id)sender {
    NSString *strURL = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";

    // 1. 建立 NSURL
    NSURL *url = [NSURL URLWithString:strURL];

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

    // 3. 指定請求方式
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];

    // 網路請求在子執行緒進行,但資料要呈現在 UI 上,
    // 因此第二個參數指定回傳到哪個佇列
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data,
                                               NSError *connectionError) {
        // data 就是請求結果,解析在 block 中進行
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:NSJSONReadingMutableContainers
                                                                    error:nil];
        NSLog(@"%@", dic);
    }];
}

五、用 block 下載圖片

- (IBAction)block:(id)sender {
    NSString *str = @"https://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";

    // 1. 建立 NSURL
    NSURL *url = [NSURL URLWithString:str];

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

    // 3. 非同步取得
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data,
                                               NSError *connectionError) {
        self.imageView.image = [UIImage imageWithData:data];
    }];
}

@end

總結

網路請求三步驟:建立 NSURL → 建立 Request → 送出並取得回應。同步與非同步的差別只在第三步選用的方法,POST 則是比 GET 多一步「把 body 加進 request」。

現在該怎麼寫

NSURLConnection 自 iOS 9 起已廢棄,新專案請改用 NSURLSession。對應關係大致如下:

// GET
NSURLSessionDataTask *task =
    [[NSURLSession sharedSession] dataTaskWithRequest:request
                                    completionHandler:^(NSData *data,
                                                        NSURLResponse *response,
                                                        NSError *error) {
        // 注意:此回呼在背景佇列,更新 UI 前請 dispatch 回主線程
    }];
[task resume];

另外三點提醒:
1. 記得呼叫 resume。NSURLSession 的 task 建立後是暫停狀態,少了這行什麼都不會發生,這是最常見的新手錯誤。
2. 字串與數值必須 URL encode。範例中的中文參數若未編碼會直接導致請求失敗,建議改用 NSURLComponents 與 NSURLQueryItem 由系統處理。
3. 同步請求會凍結 UI。它只適合在背景佇列使用;在主線程呼叫同步請求會讓 App 完全無回應,進而觸發 watchdog 終止。

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