iOS开发学习iOS Developer

iOS网络编程(四)

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

小文件下载:就以下载一个图片视频为例

1.//耗时操作[NSData dataWithContentsOfURL:url]

-(void)download1

{

//1.url

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

//2.下载二进制数据

NSData *data = [NSData dataWithContentsOfURL:url];

//3.转换

UIImage *image = [UIImage imageWithData:data];

}

2.采用发送请求获取图片,视频

//1.无法监听进度

//2.内存飙升

-(void)download2

{

//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.发送请求

[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*_Nullableresponse,NSData*_Nullabledata,NSError*_NullableconnectionError) {

//4.转换

//UIImage *image = [UIImage imageWithData:data];

//

//self.imageView.image = image;

//NSLog(@"%@",connectionError);

//4.写数据到沙盒中

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

[datawriteToFile:fullPathatomically:YES];

}];

}

3. //内存飙升,这种方法可以监听进度

-(void)download3

{

//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");

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

self.totalSize= response.expectedContentLength;

}

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

{

// NSLog(@"%zd",data.length);

[self.fileData appendData:data];

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

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

}

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

{

}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection

{

NSLog(@"connectionDidFinishLoading");

//4.写数据到沙盒中

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

[self.fileDatawriteToFile:fullPathatomically:YES];

NSLog(@"%@",fullPath);

}

1、同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,

2、异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行

上一篇下一篇

猜你喜欢

热点阅读