当前位置: 首页 > news >正文

网络编程使用代理方法 , 简化请求和响应

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

//在此之前要遵守协议<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://my.oschina.net/u/2501648/blog/541646

相关文章:

  • jsp的标签和EL表达式
  • DEBUG命令详细说明
  • 网页中多个图标在一张图片上,使用css将各图标显示
  • C++容易忽略的细节
  • vim+ctags+cscope 常用技巧和命令
  • IT公司100题-13-求链表中倒数第k个结点
  • Log aggregation has not completed or is not enabled.
  • linux安装scikit-learn
  • JavaMail:搜索、过滤接收邮件,删除邮件
  • 对JS继承的一点思考
  • 成为一名优秀的Developer的书单
  • HDU ACM 2586 How far away ?LCA-gt;并查集+Tarjan(离线)算法
  • php正则获取网页标题、关键字、网页描述代码
  • centos 6.4配置samba+ldap认证
  • 理解并取证:以太通道的动态协商机制的工作原理
  • [ 一起学React系列 -- 8 ] React中的文件上传
  • “大数据应用场景”之隔壁老王(连载四)
  • Android 控件背景颜色处理
  • Cumulo 的 ClojureScript 模块已经成型
  • Fabric架构演变之路
  • Fundebug计费标准解释:事件数是如何定义的?
  • HashMap剖析之内部结构
  • Java教程_软件开发基础
  • jquery ajax学习笔记
  • JS变量作用域
  • js作用域和this的理解
  • Lucene解析 - 基本概念
  • Python socket服务器端、客户端传送信息
  • spring学习第二天
  • storm drpc实例
  • 好的网址,关于.net 4.0 ,vs 2010
  • 基于 Babel 的 npm 包最小化设置
  • 每天一个设计模式之命令模式
  • 前端
  • 如何借助 NoSQL 提高 JPA 应用性能
  • 一天一个设计模式之JS实现——适配器模式
  • 应用生命周期终极 DevOps 工具包
  • 找一份好的前端工作,起点很重要
  • #LLM入门|Prompt#2.3_对查询任务进行分类|意图分析_Classification
  • $.ajax()
  • (1)(1.13) SiK无线电高级配置(五)
  • (2020)Java后端开发----(面试题和笔试题)
  • (22)C#传智:复习,多态虚方法抽象类接口,静态类,String与StringBuilder,集合泛型List与Dictionary,文件类,结构与类的区别
  • (C语言)strcpy与strcpy详解,与模拟实现
  • (Redis使用系列) Springboot 使用redis实现接口Api限流 十
  • (八)Docker网络跨主机通讯vxlan和vlan
  • (附源码)ssm本科教学合格评估管理系统 毕业设计 180916
  • (附源码)计算机毕业设计ssm电影分享网站
  • (转)Scala的“=”符号简介
  • (转载)OpenStack Hacker养成指南
  • .htaccess配置常用技巧
  • .NET C# 使用 SetWindowsHookEx 监听鼠标或键盘消息以及此方法的坑
  • .net core webapi Startup 注入ConfigurePrimaryHttpMessageHandler
  • .NET 中什么样的类是可使用 await 异步等待的?
  • .NET/C# 使窗口永不激活(No Activate 永不获得焦点)