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

iOS 網路請求詳解:同步、非同步與 delegate 三種寫法

編輯:iOS 開發綜合

一、兩種請求方式

  • 同步請求:請求由主執行緒發起並等待回應,網路延遲會直接卡住介面。
  • 非同步請求:請求在多執行緒中完成,回應後再回主執行緒更新 UI。

    兩者還有幾個實務差異:同步請求無法取消,非同步可以;同步無法回報進度,非同步可以透過 delegate 串流式地接收資料。

    二、基本流程

    1. 建立 NSURL 實例(包含 host、scheme、port、path 等資訊)。
    2. 產生 NSURLRequest 請求。
    3. 透過 NSURLConnection 送出。
    4. 從回傳的 NSURLResponse 與 NSError 判斷結果。
    5. 接收回應資料。

    三、同步請求

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"GET"];
    [request setURL:url];
    [request setTimeoutInterval:60];
    
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    UIImage *image = [UIImage imageWithData:data];
    self.image = image;

    寫法簡短,但因為會阻塞目前執行緒,只適合放在背景執行緒使用,絕對不要直接寫在主執行緒。

    四、非同步請求(iOS 5 以上)

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"GET"];
    [request setURL:url];
    [request setTimeoutInterval:60];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *image = [UIImage imageWithData:data];
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.image = image;
        });
    }];

    用 block 一次處理完成後的結果,程式碼最精簡。注意 UI 更新必須切回主執行緒。

    五、非同步請求(iOS 5 以前,delegate 寫法)

    - (void)setURL:(NSURL *)url {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setHTTPMethod:@"GET"];
        [request setURL:url];
        [request setTimeoutInterval:60];
    
        self.data = [NSMutableData data];
        [NSURLConnection connectionWithRequest:request delegate:self];
    }
    
    #pragma mark - NSURLConnection delegate
    
    // 資料陸續送達時反覆呼叫
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [self.data appendData:data];
    }
    
    // 全部載入完成
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        UIImage *image = [UIImage imageWithData:self.data];
        self.image = image;
    }
    
    // 失敗
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        NSLog(@"請求網絡失敗:%@", error);
    }

    幾個實務提醒

    • block 版本裡若要在主執行緒更新 UI,用 dispatch_async(dispatch_get_main_queue(), ...) 比 dispatch_sync 安全——後者在主執行緒呼叫自己會直接死鎖。
    • delegate 寫法的好處是可以拿到 expectedContentLength 做進度條,也能邊收邊解析大檔案。
    • 記得設定 timeoutInterval,並在 view controller 消失時取消請求,避免回呼打到已釋放的物件。
    • 在實際專案中,NSURLSession 已取代 NSURLConnection;上面三種寫法適合作為理解底層流程的基礎。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved