您的位置:首页 > 其它

文件下载

2015-12-29 19:36 260 查看
小文件下载方式:原因是它们有一个致命的缺点就是必须下载完成后才能返还给nsdata,也就是说无法监测到下载进度,实用性差,也就只能用于一些小文件的下载。

1.NSData dataWithContentsOfURL

2.NSURLConnection

//.NSData dataWithContentsOfURL

- (void)downloadFile{

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

// 其实这就是一个GET请求

NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/images/minion_01.png“];

NSData *data = [NSData dataWithContentsOfURL:url];

NSLog(@”%d”, data.length);

});

}

//NSURLConnection

- (void)downloadFile2{

NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/images/minion_01.png“];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

NSLog(@”%d”, data.length);

}];

}

大文件下载方式:

大文件下载方式1:(由于内存问题不可取,但需要了解)

- (void)download{

// 1.URL

NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/videos.zip“];

// 2.请求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 3.下载(创建完conn对象后,会自动发起一个异步请求)

[NSURLConnection connectionWithRequest:request delegate:self];

// [[NSURLConnection alloc] initWithRequest:request delegate:self];

// [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

// NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];//为NO 表示只是连接并没有立马开始请求,所以与 [conn start];套用

// [conn start];

}

(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event{

[self download];

}

(void)connection:(NSURLConnection )connection didFailWithError:(NSError )error{

NSLog(@”didFailWithError”);

}

1.接收到服务器的响应就会调用

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

NSLog(@”didReceiveResponse”);

// 初始化数据

self.fileData = [NSMutableData data];

// 取出文件的总长度方式1:

// NSHTTPURLResponse resp = (NSHTTPURLResponse )response;

// long long fileLength = [resp.allHeaderFields[@”Content-Length”] longLongValue];

// 取出文件的总长度方式2:

self.totalLength = response.expectedContentLength;

}

/**

* 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)

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

// 拼接数据

[self.fileData appendData:data];

// 设置进度值

// 0 ~ 1

// self.progressView.progress = (double)self.fileData.length / self.totalLength;

self.circleView.progress = (double)self.fileData.length / self.totalLength;

}

3.加载完毕后调用(服务器的数据已经完全返回后)

*/

(void)connectionDidFinishLoading:(NSURLConnection *)connection{

NSLog(@”connectionDidFinishLoading”);

// 拼接文件路径

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

NSString *file = [cache stringByAppendingPathComponent:@”videos.zip”];

// 写到沙盒中

[self.fileData writeToFile:file atomically:YES];

}

大文件下载方式2:

// 用来写数据的文件句柄对象

@property (nonatomic, strong) NSFileHandle *writeHandle;

// 文件的总大小

@property (nonatomic, assign) long long totalLength;

// 当前已经写入的文件大小

@property (nonatomic, assign) long long currentLength;

(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event{

// 1.URL

NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/music.zip“];

// 2.请求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 3.下载(创建完conn对象后,会自动发起一个异步请求)

[NSURLConnection connectionWithRequest:request delegate:self];

}

// 1.接收到服务器的响应就会调用

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

// 文件路径

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

NSString *filepath = [caches stringByAppendingPathComponent:@”videos.zip”];

// 创建一个空的文件 到 沙盒中

NSFileManager *mgr = [NSFileManager defaultManager];

[mgr createFileAtPath:filepath contents:nil attributes:nil];

// 创建一个用来写数据的文件句柄

self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];

// 获得文件的总大小

self.totalLength = response.expectedContentLength;

}

// 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)

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

// 移动到文件的最后面

[self.writeHandle seekToEndOfFile];

// 将数据写入沙盒

[self.writeHandle writeData:data];

// 累计文件的长度

self.currentLength += data.length;

NSLog(@”下载进度:%f”, (double)self.currentLength/ self.totalLength);

self.circleView.progress = (double)self.currentLength/ self.totalLength;

}

// 3.加载完毕后调用(服务器的数据已经完全返回后)

(void)connectionDidFinishLoading:(NSURLConnection *)connection{

self.currentLength = 0;

self.totalLength = 0;

// 关闭文件

[self.writeHandle closeFile];

self.writeHandle = nil;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: