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

iOS 網路訪問詳解:同步與非同步請求實作

編輯:iOS 相關資訊

一、訪問網路的方式

在 iOS 中發起網路請求主要分為兩種模式:

  • 同步請求:請求由主執行緒發起,由於網路載入需要時間,因此會阻塞主執行緒,可能造成介面卡頓。
  • 非同步請求:請求在多執行緒環境中完成,不會阻塞主執行緒。

兩者還有幾點關鍵差異:同步請求無法取消、也無法監聽載入進度;而非同步請求則可以隨時取消,並能監聽下載進度。

二、訪問網路的基本流程

  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 = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

UIImage *image = [UIImage imageWithData:data];
self.image = image;

四、非同步請求

iOS 5.0 以上可使用 GCD 搭配 sendAsynchronousRequest:queue:completionHandler: 的簡便寫法:

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_async(dispatch_get_main_queue(), ^{
        self.image = image;
    });
}];

若是較舊的系統版本,則可採用 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);
}

實務上,為了避免阻塞主執行緒、維持流暢的使用者體驗,非同步請求通常是較好的選擇。

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