首页 > 代码库 > 关于下载的五种方式
关于下载的五种方式
---恢复内容开始---
#import "ViewController.h"
#import "Campusbeaut.h"
@interface ViewController ()< NSURLConnectionDataDelegate>
{
NSMutableData *_totalData;
NSFileHandle *_fileHandle;
long long _totalLength;
UIImageView *_image;
NSData *_data;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_totalData = http://www.mamicode.com/[NSMutableData data]; //相当创建一个可变data
_image=[[UIImageView alloc]initWithFrame:self.view.bounds];
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(beaut)];
[self.view addGestureRecognizer:tap];
NSError *error;
//用它来创建一个文件
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:@"/Users/apple/Desktop/campus.jpg" contents:nil attributes:nil];
//也可以用它来创建一个文件夹
[@"" writeToFile:@"/Users/apple/Desktop/test2.db" atomically:YES encoding:NSUTF8StringEncoding error:nil];
//用它来装数据 它不能创建文件
_fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/Users/apple/Desktop/campus.jpg"];
// 方法 一
//下载到str
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSString *str=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
// NSLog(@"%@",str);
//写到文件中
NSString *path=@"/Users/apple/Desktop/test.db";
[str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
//把文件中的东西读取
NSData *data1=[NSData dataWithContentsOfFile:path];
//再把data 装化为string 当然可以直接读取给string
NSString *str1=[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding ];
// NSLog(@"--------%@",str1);
//方法 二
//把图片下载到data
_data =http://www.mamicode.com/[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D310/sign=b6af04fe0b23dd542173a169e108b3df/c9fcc3cec3fdfc03eff99b22d63f8794a5c226a2.jpg"]];
//让图片显示出来
_image.image=[UIImage imageWithData:_data];
[self.view addSubview:_image];
//把图片装在文件中
[_data writeToFile:@"/Users/apple/Desktop/camp.jpg" atomically:YES];
//方法 三
//同步方法
NSURL *url1=[NSURL URLWithString:@"http://chzich.diandian.com/post/2014-06-11/40061950061"];
//获取开始下载时间 对应俩个结束时间
CFAbsoluteTime begin=CFAbsoluteTimeGetCurrent();//第一种
NSDate *beginDate=[NSDate date];//第二种
//将路径告知请求者
NSURLRequest *request=[NSURLRequest requestWithURL:url1];
//创建响应
NSURLResponse *response;
//使用同步方法
NSData *data2=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//http响应
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;//强制类型转化
//打印响应状态
NSLog(@"status code:%d",[httpResponse statusCode]);
if ([httpResponse statusCode] == 200)
{
NSLog(@"成功下载数据");
}
//同步下载时间用的第一种方法
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"%f", end - begin);
//转化成字符串打印出来
NSString *str2=[[NSString alloc]initWithData:data2 encoding:NSUTF8StringEncoding ];
// NSLog(@"++++++++%@",str2);
//方法 四
//异步 貌似没同步复杂
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSLog(@"下载完成........");
//这个data参数就是下载数据所处地方
NSString *str3=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"========%@",str3);
NSLog(@"完成");
}];
NSLog(@"快到碗里来");
//从同步下载开始到异步下载结束所用时间 可调整开始位置的放置取得想要的时间 使用的是第二种方法 从下载时间可以实现优化程序
NSDate *endDate=[NSDate date];
NSLog(@"%f", [endDate timeIntervalSinceDate:beginDate]);
//方法 五
//它的机制也是同步的? 不过需要使用协议
NSURL *url2=[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/5ab5c9ea15ce36d3de97fa9538f33a87e850b187.jpg"];
NSURLRequest *request1=[NSURLRequest requestWithURL:url2];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request1 delegate:self];
[connection start];
}
-(void)beaut
{
//_data=http://www.mamicode.com/[NSData dataWithContentsOfFile:@"/Users/apple/Desktop/campus.jpg"];
Campusbeaut *nvnv=[[Campusbeaut alloc]init];
nvnv.Pdata=http://www.mamicode.com/self;//传值
[self presentViewController:nvnv animated:YES completion:nil ];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - NSURLConnectionDataDelegate
//4. 只有出错才会到这里
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Failed: %@", error);
}
//1. 先接受到响应信息,能够知道等下接受的数据是什么样的
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//如果是多目标下载 可以通过参数connection 来判断下载来自哪个请求
NSLog(@"Total length: %lld", [response expectedContentLength]); //网页不是正常的文件长度可能出人意料
_totalLength = response.expectedContentLength;
}
//2. 分次接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_totalData appendData:data];
[_fileHandle writeData:data]; //它们俩都可以来装图片data数据
float progress=(float)[_fileHandle offsetInFile]/_totalLength;
NSLog(@"Data: %.2f%%", progress * 100);
_data3=_totalData;
}
//3. 下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"finished...");
}
@end
---恢复内容结束---
#import "ViewController.h"
#import "Campusbeaut.h"
@interface ViewController ()< NSURLConnectionDataDelegate>
{
NSMutableData *_totalData;
NSFileHandle *_fileHandle;
long long _totalLength;
UIImageView *_image;
NSData *_data;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_totalData = http://www.mamicode.com/[NSMutableData data]; //相当创建一个可变data
_image=[[UIImageView alloc]initWithFrame:self.view.bounds];
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(beaut)];
[self.view addGestureRecognizer:tap];
NSError *error;
//用它来创建一个文件
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:@"/Users/apple/Desktop/campus.jpg" contents:nil attributes:nil];
//也可以用它来创建一个文件夹
[@"" writeToFile:@"/Users/apple/Desktop/test2.db" atomically:YES encoding:NSUTF8StringEncoding error:nil];
//用它来装数据 它不能创建文件
_fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/Users/apple/Desktop/campus.jpg"];
// 方法 一
//下载到str
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSString *str=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
// NSLog(@"%@",str);
//写到文件中
NSString *path=@"/Users/apple/Desktop/test.db";
[str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
//把文件中的东西读取
NSData *data1=[NSData dataWithContentsOfFile:path];
//再把data 装化为string 当然可以直接读取给string
NSString *str1=[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding ];
// NSLog(@"--------%@",str1);
//方法 二
//把图片下载到data
_data =http://www.mamicode.com/[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D310/sign=b6af04fe0b23dd542173a169e108b3df/c9fcc3cec3fdfc03eff99b22d63f8794a5c226a2.jpg"]];
//让图片显示出来
_image.image=[UIImage imageWithData:_data];
[self.view addSubview:_image];
//把图片装在文件中
[_data writeToFile:@"/Users/apple/Desktop/camp.jpg" atomically:YES];
//方法 三
//同步方法
NSURL *url1=[NSURL URLWithString:@"http://chzich.diandian.com/post/2014-06-11/40061950061"];
//获取开始下载时间 对应俩个结束时间
CFAbsoluteTime begin=CFAbsoluteTimeGetCurrent();//第一种
NSDate *beginDate=[NSDate date];//第二种
//将路径告知请求者
NSURLRequest *request=[NSURLRequest requestWithURL:url1];
//创建响应
NSURLResponse *response;
//使用同步方法
NSData *data2=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//http响应
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;//强制类型转化
//打印响应状态
NSLog(@"status code:%d",[httpResponse statusCode]);
if ([httpResponse statusCode] == 200)
{
NSLog(@"成功下载数据");
}
//同步下载时间用的第一种方法
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"%f", end - begin);
//转化成字符串打印出来
NSString *str2=[[NSString alloc]initWithData:data2 encoding:NSUTF8StringEncoding ];
// NSLog(@"++++++++%@",str2);
//方法 四
//异步 貌似没同步复杂
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSLog(@"下载完成........");
//这个data参数就是下载数据所处地方
NSString *str3=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"========%@",str3);
NSLog(@"完成");
}];
NSLog(@"快到碗里来");
//从同步下载开始到异步下载结束所用时间 可调整开始位置的放置取得想要的时间 使用的是第二种方法 从下载时间可以实现优化程序
NSDate *endDate=[NSDate date];
NSLog(@"%f", [endDate timeIntervalSinceDate:beginDate]);
//方法 五
//它的机制也是同步的? 不过需要使用协议
NSURL *url2=[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/5ab5c9ea15ce36d3de97fa9538f33a87e850b187.jpg"];
NSURLRequest *request1=[NSURLRequest requestWithURL:url2];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request1 delegate:self];
[connection start];
}
-(void)beaut
{
//_data=http://www.mamicode.com/[NSData dataWithContentsOfFile:@"/Users/apple/Desktop/campus.jpg"];
Campusbeaut *nvnv=[[Campusbeaut alloc]init];
nvnv.Pdata=http://www.mamicode.com/self;//传值
[self presentViewController:nvnv animated:YES completion:nil ];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - NSURLConnectionDataDelegate
//4. 只有出错才会到这里
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Failed: %@", error);
}
//1. 先接受到响应信息,能够知道等下接受的数据是什么样的
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//如果是多目标下载 可以通过参数connection 来判断下载来自哪个请求
NSLog(@"Total length: %lld", [response expectedContentLength]); //网页不是正常的文件长度可能出人意料
_totalLength = response.expectedContentLength;
}
//2. 分次接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_totalData appendData:data];
[_fileHandle writeData:data]; //它们俩都可以来装图片data数据
float progress=(float)[_fileHandle offsetInFile]/_totalLength;
NSLog(@"Data: %.2f%%", progress * 100);
_data3=_totalData;
}
//3. 下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"finished...");
}
@end