iOS开发学习iOS Developer

iOS网络编程(五)

2017-06-01  本文已影响10人  BEYOND黄

NSURLConnection大文件下载:

-(void)download

{

//1.url

// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];

NSURL*url = [NSURLURLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];

//2.创建请求对象

NSURLRequest*request = [NSURLRequestrequestWithURL:url];

//3.发送请求

[[NSURLConnectionalloc]initWithRequest:requestdelegate:self];

}

#pragma mark NSURLConnectionDataDelegate

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

{

NSLog(@"didReceiveResponse");

//1.得到文件的总大小(本次请求的文件数据的总大小)

self.totalSize= response.expectedContentLength;

//2.写数据到沙盒中

self.fullPath= [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:@"123.mp4"];

NSLog(@"%@",_fullPath);

//3.创建一个空的文件

[[NSFileManagerdefaultManager]createFileAtPath:self.fullPathcontents:nilattributes:nil];

//4.创建文件句柄(指针)

self.handle= [NSFileHandlefileHandleForWritingAtPath:self.fullPath];

}

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

{

//1.移动文件句柄到数据的末尾

[self.handleseekToEndOfFile];

//2.写数据

[self.handlewriteData:data];

//3.获得进度

self.currentSize+= data.length;

//进度=已经下载/文件的总大小

NSLog(@"%f",1.0*self.currentSize/self.totalSize);

self.progressView.progress=1.0*self.currentSize/self.totalSize;

//NSLog(@"%@",self.fullPath);

}

-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error

{

}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection

{

//1.关闭文件句柄

[self.handlecloseFile];

self.handle=nil;

NSLog(@"connectionDidFinishLoading");

NSLog(@"%@",self.fullPath);

}

上一篇下一篇

猜你喜欢

热点阅读