首页 > 代码库 > 文件下载

文件下载

1、    使用队列NSOperation下载时会将操作放在异步线程里面,不会放在主线程中

换一种方法进行下载:

- (void)download {

   self.data = http://www.mamicode.com/[NSMutableData data];

    //发送请求

    NSURL *url = [NSURL URLWithString:@"http://192.168.1.106:8080/MJServer/lufy.png"];

    NSURLRequest *reuqest = [NSURLRequest requestWithURL:url];

   [[NSURLConnection connectionWithRequest:reuqest delegate:self] start];

}

获取的数据需要进行拼接:(NSURLConnectionDataDelegate)

代理方法

1、- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [self.data appendData:data]; // 拼接下载的数据

}

2、- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    UIImage *image = [UIImage imageWithData:self.data];

    NSLog(@"下载完毕");

    self.imageView.image = image;

}

 

大文件下载

1、下载方法:

- (void)download {

    self.data = http://www.mamicode.com/[NSMutableData data]; // 初始化data

    NSURL *url = [NSURL URLWithString:@"http://192.168.1.106:8080/MJServer/movie.avi"];

    // 发送请求

    NSURLRequest *reuqest = [NSURLRequest requestWithURL:url];

    // 使用NSURLConnection创建

    [[NSURLConnection connectionWithRequest:reuqest delegate:self] start];

}

下载时使用的代理方法:

#pragma mark - 代理方法

// 开始接收数据时调用

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [self.data appendData:data]; // 拼接数据

    // 设置下载进度

    self.progressView.progress = (float)self.data.length / (float)_totalLength;

}

#pragma mark 服务器有相应就会调用这个方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    NSHTTPURLResponse *rep = (NSHTTPURLResponse *)response;

    _totalLength = [[[rep allHeaderFields] objectForKey:@"Content-Length"] intValue];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    //大文本数据存储在Caches中,不会被清除掉

    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        NSString *dir = [cacheDir stringByAppendingPathComponent:@"movie"];

        NSFileManager *mgr = [NSFileManager defaultManager];

        // 是否为文件夹

    BOOL isDir;

    // 是否存在

    BOOL exist = [mgr fileExistsAtPath:dir isDirectory:&isDir];

    if (!exist) {

        // 创建一个新的文件夹

        [mgr createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];

    }

        NSString *path = [dir stringByAppendingPathComponent:@"mj.avi"];

    // 将文件数据写入Library/Caches文件夹下

    [self.data writeToFile:path atomically:YES];

}