NSURLRequest 简单的网络请求
2018-07-20 来源:open-open
NSURLRequest 简单的网络请求
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL* url = [NSURL URLWithString:@"http://img21.mtime.cn/mg/2012/03/25/112544.76654880.jpg"];
_imageData = [[NSMutableData alloc] init];
//进度条
_pv = [[UIProgressView alloc] initWithFrame:CGRectMake(50, 50, 220, 20)];
[self.view addSubview:_pv];
[_pv release];
//创建一个请求
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
//发送请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
//接收响应头
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"接收到响应头");
[_imageData setLength:0];
//拿到响应体长度
NSHTTPURLResponse* res = (NSHTTPURLResponse*)response;
_length = [[res.allHeaderFields objectForKey:@"Content-Length"] floatValue];
NSLog(@"length:%f",_length);
//是否 开启 网络开关 状态栏的
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
//接收响应体,下载数据
/*
0 1 2 3 4 5 6 7 8 9
0 1
2 3 4
5 6 7
8 9
0 1 2 3 4 5 6 7 8 9
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"接收响应体");
//把每次下载的数据添加到一起
[_imageData appendData:data];
//刷新进度条
[_pv setProgress:_imageData.length / _length animated:YES];
}
//成功
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"成功");
UIImage* image = [UIImage imageWithData:_imageData];
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
//失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"失败");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
标签: 网络
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:iOS获取设备信息
下一篇: java金额转中文大写
最新资讯
热门推荐