码迷,mamicode.com
首页 > 其他好文 > 详细

2016 - 1 - 23 小文件下载

时间:2016-01-23 23:09:10      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

 一: 使用NSData直接下载:

    //  这种方法没法暂停,只适合下载小文件
    
    NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ];
    NSData *data =  [NSData dataWithContentsOfURL:url options:kNilOptions error:nil];
    
    UIImage *image = [UIImage imageWithData:data];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, 200, 200);
    [self.view addSubview:imageView];

 二: 使用NSURLConnect

    NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            UIImage *image = [UIImage imageWithData:data];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            imageView.frame = CGRectMake(0, 0, 200, 200);
            [self.view addSubview:imageView];
    }];
}

 三:  采用拼接代理的方法下载

  这个方法和上面的一样也只能适用于小文件的下载。

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData *fileData;

@property (nonatomic, assign) NSInteger contentLength;

//@property (nonatomic, strong) UIImage *image;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //  这种方法没法暂停,只适合下载小文件
    
    NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4" ];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    // 设置connect的代理
    [NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark - NSURLConnect 的代理

// connection接收到响应,此时应当创建数据准备拼接data
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    NSHTTPURLResponse *newResponse = response;
    // 获得文件的总长度
    self.contentLength = [newResponse.allHeaderFields[@"Content-Length"] integerValue];
    
    self.fileData = [NSMutableData data];
}

// 接收到了数据,这个方法会被多次调用,需要在这里拼接数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.fileData appendData:data];
    
    CGFloat per =   (1.0 * self.fileData.length / self.contentLength);
    NSLog(@"%f",per);
}

// 下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%zd",self.fileData.length);
}

 

2016 - 1 - 23 小文件下载

标签:

原文地址:http://www.cnblogs.com/BJTUzhengli/p/5154223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!