【iOS】檔案下載小記

來源:互聯網
上載者:User

標籤:ios   檔案   上傳   下載   cocoa touch   

檔案的下載分為NSURLConnectionNSURLSession兩種,前一種有恨悠久的曆史了。使用相對麻煩,後者是新出來的,增加了一些額外的功能。

一、NSURLConnection實現下載

TIPS:

1、當NSURLConnection下載時,得到的NSData寫入檔案時,data並沒有佔用多大記憶體. (即使檔案很大)2、一點點在傳. 做的是磁碟緩衝.而不是記憶體緩衝機制。3、瞭解在NSURLConnection上加代理。[consetDelegateQueue:[[NSOperationQueuealloc]init]]

4、NSURLResponse記錄的了url, mineType, exceptedContentLength, suggestedFileName等屬性. 下載時用得著.  

以下程式實現追蹤下載百分比的下載(URLConnection內建的方法):

#import "XNDownload.h"typedef void(^ProgressBlock)(float percent);@interface XNDownload() <NSURLConnectionDataDelegate>@property (nonatomic, strong) NSMutableData *dataM;// 儲存在沙箱中的檔案路徑@property (nonatomic, strong) NSString *cachePath;// 檔案總長度@property (nonatomic, assign) long long fileLength;// 當前下載的檔案長度@property (nonatomic, assign) long long currentLength;// 回調塊代碼@property (nonatomic, copy) ProgressBlock progress;@end@implementation XNDownload- (NSMutableData *)dataM{    if (!_dataM) {        _dataM = [NSMutableData data];    }    return _dataM;}- (void)downloadWithURL:(NSURL *)url progress:(void (^)(float))progress{    // 0. 記錄塊代碼    self.progress = progress;        // 1. request GET    NSURLRequest *request = [NSURLRequest requestWithURL:url];        // 2. connection    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];        // 讓connection支援多線程,指定代理的工作隊列即可    // NSURLConnection在運行時,運行迴圈不負責監聽代理的具體執行    [connection setDelegateQueue:[[NSOperationQueue alloc] init]];        // 3. 啟動串連    [connection start];}#pragma mark - 代理方法// 1. 接收到伺服器的響應,伺服器執行完請求,向用戶端回傳資料- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    NSLog(@"%@ %lld", response.suggestedFilename, response.expectedContentLength);    // 1. 儲存的緩衝路徑    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];    self.cachePath = [cachePath stringByAppendingPathComponent:response.suggestedFilename];    // 2. 檔案總長度    self.fileLength = response.expectedContentLength;    // 3. 當前下載的檔案長度    self.currentLength = 0;        // 清空資料    [self.dataM setData:nil];}// 2. 接收資料,從伺服器接收到資料- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    // 拼接資料    [self.dataM appendData:data];        // 根據data的長度增加當前下載的檔案長度    self.currentLength += data.length;        float progress = (float)self.currentLength / self.fileLength;        // 判斷是否定義了塊代碼    if (self.progress) {        [[NSOperationQueue mainQueue] addOperationWithBlock:^{            // 強制運行迴圈執行一次更新            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate date]];                        self.progress(progress);        }];    }}// 3. 完成接收- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"%s %@", __func__, [NSThread currentThread]);    // 將dataM寫入沙箱的緩衝目錄    // 寫入資料,NSURLConnection底層實現是用磁碟做的緩衝    [self.dataM writeToFile:self.cachePath atomically:YES];}// 4. 出現錯誤- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"%@", error.localizedDescription);}@end

二、NSURLSession實現下載

NSURLSession能實現斷點續傳,暫停下載等功能。

1、session提供的是開了多個線程的非同步下載.2、下載的暫停與續傳: (session的代理中的方法)*弄一個NSData變數來儲存下載東西.暫停時將下載任務task清空.*續傳:將暫停時的data交給session繼續下載,並將先前的data清空.3、task一定要resume才開始執行.

#import "XNViewController.h"@interface XNViewController () <NSURLSessionDownloadDelegate>// 下載網路回話@property (nonatomic, strong) NSURLSession *session;// 下載任務@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;// 續傳的位元據@property (nonatomic, strong) NSData *resumeData;@end@implementation XNViewController- (NSURLSession *)session{    if (!_session) {        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];    }    return _session;}- (void)viewDidLoad{    [super viewDidLoad];        [self downloadFile];}// 暫停下載任務- (IBAction)pause{    // 如果下載任務不存在,直接返回    if (self.downloadTask == nil) return;        // 暫停任務(塊代碼中的resumeData就是當前正在下載的位元據)    // 停止下載任務時,需要儲存資料    [self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {        self.resumeData = resumeData;                // 清空並且釋放當前的下載任務        self.downloadTask = nil;    }];}- (IBAction)resume{    // 要續傳的資料是否存在?    if (self.resumeData == nil) return;        // 建立續傳的下載任務    self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];    [self.downloadTask resume];        // 將此前記錄的續傳資料清空    self.resumeData = nil;}// 如果在開發中使用到緩衝目錄,一定要提供一個功能,“清除緩衝”!/** 下載檔案 */- (void)downloadFile{    NSString *urlStr = @"http://localhost/蒼老師全集.rmvb";    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];        NSURL *url = [NSURL URLWithString:urlStr];    // (1) 代理 & 直接啟動任    // 2. 啟動下載任務    self.downloadTask = [self.session downloadTaskWithURL:url];        [self.downloadTask resume];}#pragma mark - 下載代理方法- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{    NSLog(@"完成 %@ %@", location, [NSThread currentThread]);}/** bytesWritten               : 本次下載的位元組數 totalBytesWritten          : 已經下載的位元組數 totalBytesExpectedToWrite  : 下載總大小 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{    float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;        [[NSOperationQueue mainQueue] addOperationWithBlock:^{        //主線程中更新進度UI操作。。。。    }];}/** 續傳的代理方法 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{    NSLog(@"offset : %lld", fileOffset);}@end

出處:http://blog.csdn.net/xn4545945



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.