簡單粗暴直接上代碼
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate]] >
/** 從服務器接收到的數據 */
@property (nonatomic, strong) NSMutableData *receiveData;
/** 要下載文件的總長度 */
@property(nonatomic,assign) long long expectedContentLength;
/** 當前已經下載的字節數 */
@property(nonatomic,assign) long long currentLength;
@end
@implementation ViewController
/**
問題:
1. 沒有進度
2. 會有瞬間的內存峯值
NSURLConnection已經有10多年曆史,異步方法是從iOS 4.0開始纔有的,
在此之前都是通過"代理"方式來實現網絡連接,獲取二進制數據的
問題分析:之所以出現內存峯值,是因爲用了臨時數據拼接所有的二進制數據,意味着要下載多大的文件,就會佔用多大的內存
解決方法:每接收到一個數據包,就寫入一次文件
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1. url
NSString *urlString = @"http://192.168.32.2/11-Vim簡單演練.mp4";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
// 2. request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 網絡連接異步方法
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//
// // 將視頻文件保存到桌面
// [data writeToFile:@"/Users/apple/Desktop/123.mp4" atomically:YES];
// }];
// 傳統的代理方式
// 實例化連接對象
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;
}
// 2. 接收到服務器的二進制數據,有可能會多次
// 追加每次獲得的數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 追加數據
[self.receiveData appendData:data];
// B. 可以根據下載數據的長度,計算已經下載的長度,能夠知道百分比
self.currentLength += data.length;
// 計算百分比
float progress = (float)self.currentLength / self.expectedContentLength;
NSLog(@"%f", progress);
}
// 3. 請求加載完成,一次請求的所有資源全部獲取完成
// 將最終的數據寫入磁盤
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"加載完成");
// 將數據寫入磁盤
[self.receiveData writeToFile:@"/Users/apple/Desktop/aa.mp4" atomically:YES];
// 釋放內存
self.receiveData = nil;
}
// 4. 提示:在開發網絡應用,千萬不要忘記出錯處理!出現錯誤一定要及時通知用戶
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"發生錯誤 %@", error);
}