iOS网络编程使用代理方法 , 简化请求和响应详解手机开发
2023-06-13 09:20:07 时间
- (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];
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
-(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; }];
_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];
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
-(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; }];
3293.html
服务器部署程序员系统优化网站设置运维相关文章
- 苹果 iOS 的一 0day 漏洞售卖 5500 万元
- pytest运行_ios自动清理缓存
- ios 文件操作[通俗易懂]
- iOS 获取本地图片尺寸_ios图片处理软件
- AnyMP4 iOS Cleaner for mac(IOS文件清理工具)v1.0.16激活版
- iOS开发之——浅谈网络图片处理机制
- uniapp开发的ios应用上传app store的教程
- iOS上架app store下载步骤
- app store/ios开发证书、发布证书、推送证书的快捷制作
- iOS通过http post上传图片详解手机开发
- iOS开发笔记 – 工具篇详解手机开发
- iOS开发技巧篇详解手机开发
- 探索Linux系统:在iOS上下载(linux系统ios下载)
- Linux与iOS之间的技术对比(linux和ios)
- Linux与iOS:同源不同道(linux与ios的关系)
- iOS与Linux:新老技术的融合(ios与linux的关系)
- iOS 14最新版翻车:苹果iPhone 12系列续航大幅缩水
- 探秘iOS:它究竟是一种基于Linux的操作系统吗?(ios是linux系统吗)
- 涅槃团队掌门人高雪峰:一个iOS漏洞值多少钱
- IOS上可以安装Oracle吗(ios能装oracle吗)
- 移动端iOS技术实现Oracle数据库连接(ios联接oracle)
- 谁说 iOS 就不适用Oracle(ios oracle软件)
- 社交平台 Reddit iOS 版更新,带来类似抖音的短视频功能