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

[iOS] NSURLConnection 上手段碼:Delegate 與 Block 兩種寫法

編輯:iOS 開發綜合

iOS 7 之後蘋果推出了 NSURLSession,但為了向下相容 iOS 6,專案裡還是常常看到 NSURLConnection 的身影。它雖然已被標記為不建議使用,但理解它的運作方式,對看懂老專案或除錯仍有幫助。

寫法一:Delegate 串流式接收

這種方式會分多次回傳資料,需要自己用 NSMutableData 把片段一塊塊接起來,全部收完才由 connectionDidFinishLoading: 通知。

@interface ViewController () <NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData *receivedData;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:10.0];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        _receivedData = [NSMutableData data];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_receivedData appendData:data];
    NSLog(@"Downloading...");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Finished");
}

@end

寫法二:Block 一次性異步請求

如果只需要「把整包資料拿回來」,用 Block 版本就輕鬆多了,不用自己管理暫存緩衝區:

[NSURLConnection sendAsynchronousRequest:theRequest
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSLog(@"Finished");
}];

兩者怎麼選

Delegate 方式的優勢是可以邊收邊處理,適合大檔案下載、串流、需要回報進度的情境;Block 方式適合小請求、一次性拉取 JSON 或 XML 這類場景,程式碼量最少。

不過在真實專案中,建議直接改用 NSURLSession:它支援背景傳輸、可暫停與恢復的工作,並以 delegate 或 completion handler 兩種形態同時滿足上述需求,是目前的標準做法。

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