iT邦幫忙

0

iOS APP 開發 OC 第九天,網路請求原理

tags: OC 30 day


因為工作的需求,今天跳級來寫寫網路請求。

NSURLConnection

我們利用這個類,幫我們發送請求。
他總共有兩個類方法:

  1. Sync 同步
  2. Asyn 異步
    那我們發送網路請求要用哪一個呢?
    Asyn 異步,因為網路請求,會比較慢。
    我們選擇完後,會創建一個線程。

    看見的一個參數,必須放入一個網路請求。
NSURLRequest *request = [NSURLRequest requestWithURL:<#(nonnull NSURL *)#>]

於是,我們創建一個網路請求,網路請求裡面也有一個參數,這個參數是什麼呢? URL
於是做了一個URL

NSURL *url = [NSURL URLWithString:@"https://tw.yahoo.com"];

把URL帶入網路請求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

第二個參數使用主隊列。

[NSOperationQueue mainQueue]

第三個參數cpmpletionHandler裡面有三個參數
//reponse
//data
//connectionError

完整的網路請求編碼如下:

    //發送請求
    NSURL *url = [NSURL URLWithString:@"https://tw.yahoo.com"];
    //請求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //發送異步請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        //reponse
        //data
        //connectionError
        if(!connectionError){
            NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",html);
        }else{
            NSLog(@"連接錯誤 %@",connectionError);
        }
    }];

執行看看


很順利的拿到一大串資料了。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言