iOS之小文件下载

Posted 学东哥哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS之小文件下载相关的知识,希望对你有一定的参考价值。

#import "ViewController.h"

@interface ViewController () <NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 文件数据 */
@property (nonatomic, strong) NSMutableData *fileData;
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger contentLength;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/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);
    self.progressView.progress = progress;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"下载完毕");
    
    // 将文件写入沙盒中
    
    // 缓存文件夹
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    // 文件路径
    NSString *file = [caches stringByAppendingPathComponent:@"minion_15.mp4"];
    
    // 写入数据
    [self.fileData writeToFile:file atomically:YES];
    self.fileData = nil;
}

- (void)connDownload
{
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png"];
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%zd", data.length);
    }];
}

- (void)dataDownlaod
{
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png"];
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    NSLog(@"%zd", data.length);
}

@end

 

以上是关于iOS之小文件下载的主要内容,如果未能解决你的问题,请参考以下文章

猫猫学iOS之小知识iOS启动动画_Launch Screen的运用

猫猫学iOS之小知识之xcode6自己主动提示图片插件 KSImageNamed的安装

python学习之旅-06 之小数据池,编码

Apache Iceberg入门教程系列之小文件合并

猫猫学iOS之小知识之_xcode插件的删除方法_自己主动提示图片插件KSImageNamed有时不灵_分类或宏之类不能自己主动提示,

Python基础之小数据池及深浅拷贝