NSURLConnection小文件下載寫入沙盒

使用delegate的方式:

@interface ViewController () <NSURLConnectionDataDelegate>
/** 文件數(shù)據(jù) */
@property (nonatomic, strong) NSMutableData *fileData;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger contentLength;
@end

<NSURLConnectionDataDelegate>相關(guān)代理方法實現(xiàn):

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/videos/minion_15.mp4"];
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
}

#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
    self.fileData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.fileData appendData:data];
    CGFloat progress = 1.0 * self.fileData.length / self.contentLength;
    NSLog(@"已下載:%.2f%%", (progress) * 100);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"下載完畢");
    // 將文件寫入沙盒中
    // 緩存文件夾
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // 文件路徑
    NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.mp4"];
    NSLog(@"%@",file);
    // 寫入數(shù)據(jù)
    [self.fileData writeToFile:file atomically:YES];
    self.fileData = nil;
}

如果要下載的文件足夠小:

- (void)dataDownlaod{
    NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/images/minion_15.png"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.png"];
    [data writeToFile:file atomically:YES];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,353評論 25 708
  • 使用NSURLConnection實現(xiàn)下載 1. 小文件下載 第一種方式(NSData) 第二種方式(NSURLC...
    擱淺的青蛙閱讀 1,979評論 3 10
  • 身為五音不全,高音上不去,低音下不來的小編,每每看到有人在舞臺上一展歌喉都羨慕不已。 有人唱歌能登報紙,小編唱歌卻...
    至尚純K靚飯式KTV閱讀 511評論 0 1
  • 我有很多我放不下的事情,我放不下曾經(jīng)付出的真心卻換來一個無言的背叛。我放不下自己曾經(jīng)的努力卻換不回一絲的回報?!?..
    紫蝶_閱讀 306評論 0 0