NSURLConnection 下載文件增強版 之所以叫加強版,適應爲優化了內存,沒有了內存峯值
優化的地方在每一次下載好之後立馬就寫到了本地
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate]] >
/** 從服務器接收到的數據 */
@property (nonatomic, strong) NSMutableData *receiveData;
/** 要下載文件的總長度 */
@property(nonatomic,assign) long long expectedContentLength;
/** 當前已經下載的字節數 */
@property(nonatomic,assign) long long currentLength;
/** 保存文件的路徑 */
@property (nonatomic, copy) NSString *targetPath;
@end
@implementation ViewController
/**
問題:
1. 沒有進度
2. 會有瞬間的內存峯值
NSURLConnection已經有10多年曆史,異步方法是從iOS 4.0開始纔有的,
在此之前都是通過"代理"方式來實現網絡連接,獲取二進制數據的
問題分析:之所以出現內存峯值,是因爲用了臨時數據拼接所有的二進制數據,意味着要下載多大的文件,就會佔用多大的內存
解決方法:每接收到一個數據包,就寫入一次文件
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1. url
NSString *urlString = @"http://127.0.0.1/01.C語言-語法預覽.mp4";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
// 2. request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
// 啓動連接
[connection start];
}
#pragma mark - 網絡連接代理方法
// 1. 接收到服務器的響應,服務器會告訴客戶端,有關請求資源的一些信息
// URL 客戶端請求的資源路徑
// *** MIMEType 服務器告訴客戶端,應該用什麼軟件可以打開二進制數據,例如Flash,需要安裝插件之後才能夠看到
// 之所以能夠豐富多彩,是因爲有足夠多的軟件能夠打開不同的二進制數據
// expectedContentLength 期望的內容長度,通常對於下載來說,就是要下載的文件長度
// textEncodingName 文本編碼名稱,對於html,text其他格式的文本文件,可以知道用什麼軟件打開,並使用對應的編碼
// suggestedFilename 建議的文件名
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"服務器響應");
self.receiveData = [[NSMutableData alloc] init];
// A. 記錄住要下載文件的總長度
self.expectedContentLength = response.expectedContentLength;
self.currentLength = 0;
// 生成保存文件的完整路徑
self.targetPath = [@"/Users/apple/Desktop" stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@",response.suggestedFilename);
// 將原有文件刪除,這個方法如果文件不存在,就什麼也不做,也不會出錯!
[[NSFileManager defaultManager] removeItemAtPath:self.targetPath error:NULL];
}
// 2. 接收到服務器的二進制數據,有可能會多次
// 追加每次獲得的數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 追加數據
// [self.receiveData appendData:data];
// B. 可以根據下載數據的長度,計算已經下載的長度,能夠知道百分比
self.currentLength += data.length;
// 將數據寫入磁盤
[self writeToFileWithData:data];
// 計算百分比
//float progress = (float)self.currentLength / self.expectedContentLength;
//NSLog(@"%f", progress);
}
/** 將 data 寫入目標文件 */
- (void)writeToFileWithData:(NSData *)data
{
// 1. NSFileManager => 文件的複製,刪除,檢查是否存在,遍歷子目錄……文件級的操作
// 2. 針對一個文件進行讀寫操作 "Handle" 句柄
NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.targetPath];
// 如果文件不存在,句柄會爲空,就不能用fp操作文件
if (fp == nil)
{
// 直接將二進制數據寫入文件,文件同時就會被創建
[data writeToFile:self.targetPath atomically:YES];
}
else
{
// 將文件操作指針移動到文件末尾
[fp seekToEndOfFile];
// 將數據追加寫入文件
[fp writeData:data];
// 關閉文件,如果針對文件級的讀寫,在C語言中,一定記住關閉
[fp closeFile];
}
}
// 3. 請求加載完成,一次請求的所有資源全部獲取完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"加載完成");
}
// 4. 提示:在開發網絡應用,千萬不要忘記出錯處理!出現錯誤一定要及時通知用戶
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"發生錯誤 %@", error);
}
@end