首页 > 其他 > 详细

文件下载

时间:2014-07-12 12:52:37      阅读:386      评论:0      收藏:0      [点我收藏+]

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

换一种方法进行下载:

- (void)download {

   self.data = [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 = [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];

}

文件下载,布布扣,bubuko.com

文件下载

原文:http://www.cnblogs.com/angongIT/p/3832716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!