iOS 檔案下載

來源:互聯網
上載者:User

標籤:rdo   ted   word   queue   isp   nsobject   creat   sel   ring   

最為原始的檔案下載
第一步:
使用MD5對url加密
NSString+Password.h

#import <Foundation/Foundation.h>@interface NSString (Password)/** *  32位MD5加密 * *  @return 32位MD5加密結果 */- (NSString *)MD5;/** *  SHA1加密 * *  @return SHA1加密結果 */- (NSString *)SHA1;@end
#import "NSString+Password.h"#import <CommonCrypto/CommonDigest.h>@implementation NSString (Password)#pragma mark 使用MD5加密字串- (NSString *)MD5{    const char *cStr = [self UTF8String];    unsigned char digest[CC_MD5_DIGEST_LENGTH];    CC_MD5(cStr, strlen(cStr), digest);    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {        [result appendFormat:@"%02x", digest[i]];    }    return result;}#pragma mark 使用SHA1加密字串- (NSString *)SHA1{    const char *cStr = [self UTF8String];    NSData *data = [NSData dataWithBytes:cStr length:self.length];    uint8_t digest[CC_SHA1_DIGEST_LENGTH];    CC_SHA1(data.bytes, data.length, digest);    NSMutableString *result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {        [result appendFormat:@"%02x", digest[i]];    }    return result;}@end

封裝下載工具類

FileDownload
#import <Foundation/Foundation.h>@interface FileDownload : NSObject- (void)downloadFileWithURL:(NSURL *)url completion:(void (^)(UIImage *image))completion;@end
#import "FileDownload.h"#import "NSString+Password.h"#define kTimeOut        2.0f// 每次下載的位元組數#define kBytesPerTimes  20250@interface FileDownload()@property (nonatomic, strong) NSString *cacheFile;@property (nonatomic, strong) UIImage *cacheImage;@end@implementation FileDownload/** 為了保證開發的簡單,全部方法都不使用多線程,全部的注意力都保持在檔案下載上 在開發中假設碰到比較繞的計算問題時,建議: 1> 測試資料不要太大 2> 測試資料的數值變化,可以用筆算計算出準確的數值 3> 編寫代碼對比測試 *///- (NSString *)cacheFile//{//    if (!_cacheFile) {//        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];//        _cacheFile = [cacheDir stringByAppendingPathComponent:@"123.png"];//    }//    return _cacheFile;//}- (UIImage *)cacheImage{    if (!_cacheImage) {        _cacheImage = [UIImage imageWithContentsOfFile:self.cacheFile];    }    return _cacheImage;}- (void)setCacheFile:(NSString *)urlStr{    NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];    urlStr = [urlStr MD5];    _cacheFile = [cacheDir stringByAppendingPathComponent:urlStr];}- (void)downloadFileWithURL:(NSURL *)url completion:(void (^)(UIImage *image))completion{    // GCD中的串列隊列非同步方法呼叫    dispatch_queue_t q = dispatch_queue_create("cn.itcast.download", DISPATCH_QUEUE_SERIAL);    dispatch_async(q, ^{        NSLog(@"%@", [NSThread currentThread]);        // 把對URL進行MD5加密之後的結果當成檔案名稱        self.cacheFile = [url absoluteString];        // 1. 從網路下載檔案,須要知道這個檔案的大小        long long fileSize = [self fileSizeWithURL:url];        // 計算本機快取檔案大小        long long cacheFileSize = [self localFileSize];        if (cacheFileSize == fileSize) {            dispatch_async(dispatch_get_main_queue(), ^{                completion(self.cacheImage);            });            NSLog(@"檔案已經存在");            return;        }        // 2. 確定每一個資料包的大小        long long fromB = 0;        long long toB = 0;        // 計算起始和結束的位元組數        while (fileSize > kBytesPerTimes) {            // 20480 + 20480            //            toB = fromB + kBytesPerTimes - 1;            // 3. 分段下載檔案            [self downloadDataWithURL:url fromB:fromB toB:toB];            fileSize -= kBytesPerTimes;            fromB += kBytesPerTimes;        }        [self downloadDataWithURL:url fromB:fromB toB:fromB + fileSize - 1];        dispatch_async(dispatch_get_main_queue(), ^{            completion(self.cacheImage);        });            });}#pragma mark 下載指定位元組範圍的資料包/** NSURLRequestUseProtocolCachePolicy = 0,        // 預設的緩衝策略,記憶體緩衝 NSURLRequestReloadIgnoringLocalCacheData = 1,  // 忽略本地的記憶體緩衝 NSURLRequestReloadIgnoringCacheData */- (void)downloadDataWithURL:(NSURL *)url fromB:(long long)fromB toB:(long long)toB{    NSLog(@"資料包:%@", [NSThread currentThread]);    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeOut];    // 指定請求中所要GET的位元組範圍    NSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld", fromB, toB];    [request setValue:range forHTTPHeaderField:@"Range"];    NSLog(@"range----%@", range);    NSURLResponse *response = nil;    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];    // 寫入檔案,覆蓋檔案不會追加//    [data writeToFile:@"/Users/aplle/Desktop/1.png" atomically:YES];    [self appendData:data];    NSLog(@"response*******%@", response);}#pragma mark - 讀取本機快取檔案大小- (long long)localFileSize{    // 讀取本地檔案資訊    NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:self.cacheFile error:NULL];    NSLog(@"讀取本地檔案資訊%lld", [dict[NSFileSize] longLongValue]);    return [dict[NSFileSize] longLongValue];}#pragma mark - 追加資料到檔案- (void)appendData:(NSData *)data{    // 推斷檔案是否存在    NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cacheFile];    // 假設檔案不存在建立檔案    if (!fp) {        [data writeToFile:self.cacheFile atomically:YES];    } else {        // 假設檔案已經存在追加檔案        // 1> 移動到檔案末尾        [fp seekToEndOfFile];        // 2> 追加資料        [fp writeData:data];        // 3> 寫入檔案        [fp closeFile];    }}#pragma mark - 擷取網路檔案大小- (long long)fileSizeWithURL:(NSURL *)url{    // 預設是GET    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeOut];    // HEAD 頭,僅僅是返迴文件資源的資訊,不返回詳細是資料    // 假設要擷取資源的MIMEType,也必須用HEAD,否則,資料會被反覆下載兩次    request.HTTPMethod = @"HEAD";    // 使用同步方法擷取檔案大小    NSURLResponse *response = nil;    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];    // expectedContentLength檔案在網路上的大小    NSLog(@"%lld", response.expectedContentLength);        return response.expectedContentLength;}@end

使用工具類進行下載檔案

#import "MJViewController.h"#import "FileDownload.h"@interface MJViewController ()@property (nonatomic, strong) FileDownload *download;@property (weak, nonatomic) IBOutlet UIImageView *imageView;@end@implementation MJViewController- (void)viewDidLoad{    [super viewDidLoad];    self.download = [[FileDownload alloc] init];    // http://image.zcool.com.cn/56/13/1308200901454.jpg    [self.download downloadFileWithURL:[NSURL URLWithString:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"] completion:^(UIImage *image) {        self.imageView.image = image;    }];}@end

iOS 檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.