NSURLConnection 提供了兩條下載路徑:一條阻塞當前線程直到完成,一條基於代理回調非阻塞執行。理解兩者的差異,才能選對場景。
#import <UIKit/UIKit.h>
@interface ios23_downViewController : UIViewController
<NSURLConnectionDelegate, NSURLConnectionDataDelegate> {
NSMutableData *connectionData;
}
- (IBAction)tongbu;
- (IBAction)yibu;
@property (nonatomic, retain) NSMutableData *connectionData;
@end
- (IBAction)tongbu
{
NSLog(@"同步");
NSError *err;
NSString *url = @"https://172.22.65.38/new/1.doc";
NSURL *fileUrl = [NSURL URLWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:fileUrl];
// 該方法會阻塞當前線程,直到請求返回
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&err];
if (data.length > 0) {
NSString *savePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"documents"]
stringByAppendingPathComponent:@"test.zip"];
if ([data writeToFile:savePath atomically:YES]) {
NSLog(@"保存成功");
} else {
NSLog(@"保存失敗");
}
}
}
- (IBAction)yibu
{
NSLog(@"異步");
NSString *url = @"https://172.22.65.38/new/1.doc";
NSURL *fileUrl = [NSURL URLWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:fileUrl];
// 創建連接後立即返回,結果通過代理回調送達
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
connectionData = [[NSMutableData alloc] init];
}
// 分塊接收數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[connectionData appendData:data];
}
// 全部接收完畢,落盤
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connectionData.length > 0) {
NSString *savePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"documents"]
stringByAppendingPathComponent:@"test.zip"];
if ([connectionData writeToFile:savePath atomically:YES]) {
NSLog(@"保存成功");
} else {
NSLog(@"保存失敗");
}
}
}
// 失敗回調
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"下載失敗:%@", error);
}
同步方式代碼最短,但會凍結主線程,界面直接卡住不動,只適合寫命令行工具或在後台隊列裡執行。異步方式不會阻塞,並且能通過 didReceiveData: 分塊累積,天然支持進度計算與大文件下載,是 App 內的正確選擇。
需要指出的是,NSURLConnection 從 iOS 9 起已被蘋果正式廢棄,新項目請改用 NSURLSession。對應的寫法更簡潔:
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithURL:fileUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error && data.length > 0) {
[data writeToFile:savePath atomically:YES];
}
}];
[task resume];
若下載的是大文件,更應使用 downloadTaskWithURL:completionHandler:,由系統直接寫入臨時文件並支持斷點續傳,避免把整份數據堆在內存裡。示例中的 URL 是內網地址,僅供本地測試;正式環境記得使用 HTTPS。