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

iOS 網路編程:以 NSURLConnection 實作非同步 GET 請求

編輯:iOS 開發綜合

同步請求雖然寫法簡單,但會把主執行緒卡住。要讓 App 在抓資料的同時畫面仍能操作,就必須改用非同步連線。NSURLConnection 的非同步模式透過 delegate 回呼把「資料一段段到齊」的過程交給開發者處理。

三個關鍵回呼

connection:didReceiveData: 收到資料時呼叫。若回應很大,這個方法會被多次呼叫,每次給你一小塊。

connection:didFailWithError: 載入過程中發生錯誤時呼叫。

connectionDidFinishLoading: 全部資料收完後呼叫,必定在最後一次 didReceiveData 之後,此時暫存區的資料才是完整的。

介面宣告

由於要用 delegate 模式,主視圖控制器必須宣告遵循 NSURLConnectionDelegate 協議。datas 之所以宣告成可變資料型別,就是為了在資料陸續送達時不斷 append。

#import <UIKit/UIKit.h>
#import "NSString+URLEncoding.h"
#import "NSNumber+Message.h"

@interface MasterViewController : UITableViewController <NSURLConnectionDelegate>

@property (strong, nonatomic) DetailViewController *detailViewController;

// 保存要顯示的資料列表
@property (nonatomic, strong) NSMutableArray *listData;

// 暫存從伺服器接收到的原始資料
@property (strong, nonatomic) NSMutableData *datas;

// 重新載入表視圖
- (void)reloadView:(NSDictionary *)res;

// 開始請求 Web Service
- (void)startRequest;

@end

實作

#pragma mark - 發出請求

- (void)startRequest {
    NSString *strURL = [[NSString alloc] initWithFormat:
        @"https://iosbook3/mynotes/webservice.php?email=%@&type=%@&action=%@",
        @"你的帳號信箱", @"JSON", @"query"];

    NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        _datas = [NSMutableData new];
    }
}

#pragma mark - NSURLConnection 回呼

// 資料可能分多次送達,要持續累加
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_datas appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%@", [error localizedDescription]);
}

// 資料完整抵達,可以進行解析
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"請求完成…");
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_datas
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
    [self reloadView:dict];
}

為什麼一定要用 appendData

這是初學者最容易搞錯的地方。didReceiveData 拿到的只是「這一批」資料,不是全部,所以必須用 appendData: 累加到暫存物件,而不是直接指派覆蓋。等到 connectionDidFinishLoading 觸發,_datas 才是完整的回應內容,也才適合交給表示層去解析與刷新畫面。

現代的替代方案

NSURLConnection 已被蘋果標記為 deprecated。新專案請改用 NSURLSession,用 dataTaskWithRequest:completionHandler: 一行就能取代上面三個回呼;若仍想沿用 delegate 模式,NSURLSessionDataDelegate 也提供了 didReceiveData 與 didCompleteWithError 的對應方法。

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