iOS网络编程使用代理方法 , 简化请求和响应详解手机开发

//在此之前要遵守协议<NSURLConnectionDataDelegate> 
#import "ViewController.h" 
#import "Cricl.h" 
@interface ViewController (){ 
UITextField *_textField; 
UIProgressView *_progressView; 
UILabel *_label; 
UIButton *_button; 
Cricl *cricl; 
long long _totalLength; 
NSMutableData *_data; 
UIImageView *imageOne; 
UIImageView *imageTwo; 
UIImageView *imageThree; 
UIButton *buttonpause; 
BOOL num; 
NSTimer *timer; 
} 
@end 
@implementation ViewController 
- (void)viewDidLoad { 
cricl = [[Cricl alloc]initWithFrame:CGRectMake(70,130, 375, 100)]; 
cricl.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:0]; 
imageOne = [[UIImageView alloc]initWithFrame:CGRectMake(20, 300, 160, 120)]; 
[self.view addSubview:imageOne]; 
imageTwo = [[UIImageView alloc]initWithFrame:CGRectMake(195, 300, 160, 120)]; 
[self.view addSubview:imageTwo]; 
imageThree = [[UIImageView alloc]init]; 
[self.view addSubview:cricl]; 
[super viewDidLoad]; 
[self layout];//页面布局 
} 
-(void)layout{ 
self.view.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1]; 
//地址栏 
_textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 355, 25)]; 
_textField.borderStyle = UITextBorderStyleRoundedRect;//文本框边框样式(圆弧) 
_textField.text = @"http://i-7.vcimg.com/trim/f7a6fc6ebf36475798dd3bf726288d5988839/trim.jpg"; 
[self.view addSubview:_textField]; 
_label = [[UILabel alloc]initWithFrame:CGRectMake(10, 110, 80, 25)]; 
//    _label.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:0.6]; 
_label.text = @"正在下载"; 
_label.font = [UIFont fontWithName:@"Arial" size:20]; 
[self.view addSubview:_label]; 
_progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(30, 400, 335, 25)]; 
//    [self.view addSubview:_progressView]; 
_button.layer.backgroundColor = [UIColor blackColor].CGColor; 
_button = [[UIButton alloc]initWithFrame:CGRectMake(10, 500, 355, 25)]; 
[_button setTitle:@"下载" forState:UIControlStateNormal]; 
_button.backgroundColor = [UIColor colorWithRed:0.8 green:0.5 blue:0.7 alpha:0.6]; 
[_button addTarget:self action:@selector(choose) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:_button]; 
buttonpause = [[UIButton alloc]initWithFrame:CGRectMake(20, 600, 60, 25)]; 
buttonpause.backgroundColor = [UIColor colorWithRed:0.8 green:0.5 blue:0.7 alpha:0.6]; 
[buttonpause setTitle:@"暂停" forState:UIControlStateNormal]; 
[buttonpause addTarget:self action:@selector(okpause) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:buttonpause]; 
} 
#pragma mark 更新进度条 
-(void)updateProgress{ 
if(_data.length == _totalLength){ 
_label.text = @"下载完成"; 
} 
else{ 
_label.text = @"正在下载"; 
} 
cricl.value = (float)_data.length/_totalLength*2*M_PI; 
} 
#pragma mark 发送数据请求 
-(void)choose{ 
NSLog(@"下载中..."); 
NSString *urlStr; 
if(num){ 
urlStr= @"http://i-7.vcimg.com/trim/867a1fe997bf3baeebbd223ae9aecdc8142598/trim.jpg"; 
} 
else{ 
urlStr=@"http://i-7.vcimg.com/trim/f7a6fc6ebf36475798dd3bf726288d5988839/trim.jpg"; 
} 
//对于url中的中文是无法解析的,需要进行url编码 
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
//    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSetURLQueryAllow] 
//创建url链接 
NSURL *url = [NSURL URLWithString:urlStr]; 
//创建请求request 
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f]; 
//创建链接 
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 
//启动连接 
[connection start]; 
} 
#pragma mark -开始代理方法 
#pragma mark -开始响应 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 
NSLog(@"接收响应"); 
_data = [[NSMutableData alloc]init]; 
//初始化,设置进度条进度 
cricl.value = 0; 
//处理响应 
NSLog(@"%@",response); 
//通过响应头中的content-Length取得整个响应的总长度 
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
NSDictionary *HeaderFields = [httpResponse allHeaderFields]; 
NSLog(@"%@",HeaderFields); 
_totalLength = [HeaderFields[@"Content-Length"] longLongValue]; 
//    NSLog(@"%lld",_totalLength); 
} 
#pragma mark 接收响应数据 
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
NSLog(@"接收响应数据"); 
[_data appendData:data]; 
//更新进度条 
[self updateProgress]; 
} 
#pragma mark 数据接收完成 
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
NSLog(@"数据接收完成"); 
//数据接收完保存文件(注意苹果官方要求:下载数据智能保存到缓存目录) 
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
NSLog(@"%@",path); 
path=[path stringByAppendingPathComponent:@"下载图片01.jpg"]; 
//保存下载内容 
[_data writeToFile:path atomically:YES]; 
if(num){ 
imageOne.image = [UIImage imageWithData:_data]; 
num = NO; 
} 
else{ 
imageTwo.image = [UIImage imageWithData:_data]; 
num = YES; 
} 
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(convert) userInfo:nil repeats:YES]; 
} 
#pragma mark 请求失败 
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 
NSLog(@"请求失败:%@",error); 
} 
-(void)okpause{ 
[timer invalidate]; 
timer = nil; 
} 
-(void)convert{ 
NSDate *date = [[NSDate alloc]init]; 
imageThree.image = imageOne.image; 
imageOne.image = imageTwo.image; 
imageTwo.image = imageThree.image; 
NSLog(@"%@",date); 
} 
#import "Cricl.h" 
@implementation Cricl 
- (void)drawRect:(CGRect)rect { 
CGContextRef context = UIGraphicsGetCurrentContext(); 
[self drawArc:context]; 
} 
-(void)setValue:(float)value{ 
_value = value; 
[self setNeedsDisplay]; 
} 
-(void)drawArc:(CGContextRef)context{ 
CGContextMoveToPoint(context, 220/2.0, 100/2.0); 
[[UIColor redColor]set]; 
CGContextAddArc(context, 220/2.0, 100/2.0, 100/2.0, 0, _value, 0); 
CGContextDrawPath(context, kCGPathFillStroke); 
} 
@end 
//简化请求和响应 
#import "ViewController.h" 
@interface ViewController (){ 
UILabel *_label; 
UIButton *_button; 
UITextField *_field; 
long long _totalLength; 
UIImageView *imageOne; 
UIImageView *imageTwo; 
BOOL num; 
} 
@end 
@implementation ViewController 
- (void)viewDidLoad { 
[super viewDidLoad]; 
[self layout]; 
} 
-(void)layout{ 
imageOne =[[UIImageView alloc]initWithFrame:CGRectMake(20, 300, 100, 100)]; 
[self.view addSubview:imageOne]; 
imageTwo = [[UIImageView alloc]initWithFrame:CGRectMake(150, 300, 100, 100)]; 
[self.view addSubview:imageTwo]; 
_field = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 355, 25)]; 
_field.borderStyle = UITextBorderStyleRoundedRect; 
_field.text = @"http://5.26923.com/download/pic/000/328/ba80a24af0d5aba07e1461eca71f9502.jpg"; 
[self.view addSubview:_field]; 
_label = [[UILabel alloc]initWithFrame:CGRectMake(10, 90, 100, 25)]; 
_label.text = @"图片"; 
[self.view addSubview:_label]; 
_button = [[UIButton alloc]initWithFrame:CGRectMake(10,500, 355, 25)]; 
_button.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:0.6]; 
[_button setTitle:@"正在下载" forState:UIControlStateNormal]; 
[_button addTarget:self action:@selector(sendRequst) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:_button]; 
} 
-(void)sendRequst{ 
//发送网址,并将其转换成utf8网络字节序 
NSString *urlStr = _field.text; 
NSLog(@"xxxx%@",urlStr); 
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
//连接与网络 
NSURL *url = [NSURL URLWithString:urlStr]; 
//发送请求和网络 
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f]; 
//同步所表示文件原件的发送必须到达才可执行下一步,异步可以进行后台 
//发送异步请求 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
NSLog(@"%@",path); 
path = [path stringByAppendingPathComponent:@"图片01.jpg"]; 
[data writeToFile:path atomically:YES]; 
NSLog(@"%i",num); 
if(num){ 
imageOne.image = [UIImage imageWithData:data]; 
num = NO; 
}else{ 
imageTwo.image = [UIImage imageWithData:data]; 
num= YES; 
} 
}]; 
} 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/3293.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论