注意:
NSURLConnectionDownloadDelegate 千萬不要用!!! 專門針對雜志的下載提供的接口
如果在開發(fā)中使用DownloadDelegate 下載.能夠監(jiān)聽下載進(jìn)度,但是無法拿到下載文件!
Newsstand Kit’s 專門用來做雜志!!!
問題:
1.沒有下載進(jìn)度 ,會影響用戶體驗
2.內(nèi)存偏高,有一個最大峰值:
解決辦法:
- 通過代理方式來解決!!
1.進(jìn)度跟進(jìn)!
- 在響應(yīng)方法中獲得文件總大小!
- 每次接收到數(shù)據(jù),計算數(shù)據(jù)的總比例!
2.保存文件的思路?
- 保存完成寫入磁盤
測試結(jié)果:和異步方法執(zhí)行的效果一樣.仍然存在內(nèi)存問題!
推測:蘋果的異步方法的實現(xiàn)思路.就是剛才我們的實現(xiàn)思路!!
- 邊下載,邊寫
1.NSFileHandle 測地解決了內(nèi)存峰值的問題!
2.NSOutputStream 輸出流
實現(xiàn)NSURLConnectionDataDelegate
#pragma mark - <NSURLConnectionDataDelegate>
//1.接受到服務(wù)器的響應(yīng) - 狀態(tài)行&響應(yīng)頭 - 做一些準(zhǔn)備工作
//expectedContentLength 需要下載文件的總大小 long long
//suggestedFilename 服務(wù)器建議保存的文件名稱
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@",response);
//記錄文件總大小
self.expectedContentLength = response.expectedContentLength;
self.currentLength = 0;
//生成目標(biāo)文件路徑
self.tartgetFilePath = [@"/Users/h/Desktop/123" stringByAppendingPathComponent:response.suggestedFilename];
//刪除 removeItemAtPath 如果文件存在,就會直接刪除,如果文件不存在,就什么也不做!!也不會報錯!
[[NSFileManager defaultManager] removeItemAtPath:self.tartgetFilePath error:NULL];
//輸出流 以追加的方式打開文件流
self.fileStream = [[NSOutputStream alloc]initToFileAtPath:self.tartgetFilePath append:YES];
[self.fileStream open];
}
//2.接受到服務(wù)器的數(shù)據(jù) - 此代理方法可能會執(zhí)行很多次!! 因為拿到多個data
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
self.currentLength += data.length;
//計算百分比
// progress = long long / long long
float progress = (float)self.currentLength / self.expectedContentLength;
NSLog(@"%f",progress);
//將數(shù)據(jù)追加到文件流中
[self.fileStream write:data.bytes maxLength:data.length];
}
//3.所有的數(shù)據(jù)加載完畢 - 所有數(shù)據(jù)都傳輸完畢,只是一個最后的通知
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"完畢");
//關(guān)閉文件流
[self.fileStream close];
}
//4.下載失敗或者錯誤
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}