zoukankan      html  css  js  c++  java
  • IOS网络访问详解

    第一、访问网络的方式

    同步请求:数据的请求过程是由主线程发起的,网络加载需要一定的时间,因此会堵塞主线程

    异步请求:数据的请求在多线程中完成

    同步请求无法取消,异步请求的过程中可以取消,同步请求无法监听加载进度,异步请求可以监听

    第二、访问网络的基本流程

    构造NSURL实例

    生成NSURLRequest请求

    通过NSURLConnection发送请求

    通过返回NSURLRespond实例和NSErro实例分析结果

    接受返回数据

    NSURL实例包含了地址信息,如host、scheme、relativePath、port、path

    第三、同步请求

        NSMutableURLRequest *request=[[NSMutableURLRequest alloc] init];
        [request setHTTPMethod:@"GET"];
        [request setURL:url];
        [request setTimeoutInterval:60];
        
        NSURLResponse *response;
        NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        UIImage *image=[UIImage imageWithData:data];
        self.image=image;
    


    第四、异步请求

    5.0以上支持

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc] init];
        [request setHTTPMethod:@"GET"];
        [request setURL:url];
        [request setTimeoutInterval:60];
        
        NSOperationQueue *queue=[[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:request queue: queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            UIImage *image=[UIImage imageWithData:data];
                  dispatch_sync(dispatch_get_main_queue(), ^{
                      self.image=image;
                  });
        }];
    


    5.0一下代码实现:

    - (void)setURL:(NSURL *)url {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        //设置请求方式
        [request setHTTPMethod:@"GET"];
        
        [request setURL:url];
        //设置超时时间
        [request setTimeoutInterval:60];
    
        self.data = [NSMutableData data];
        //发送一个异步请求
        [NSURLConnection connectionWithRequest:request delegate:self];
    }
    
    #pragma mark - NSURLConnection delegate
    //数据加载过程中调用
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [self.data appendData:data];
    }
    
    //数据加载完成后调用
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        UIImage *image = [UIImage imageWithData:self.data];
        self.image = image;
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        NSLog(@"请求网络失败:%@",error);
    }
    
    


  • 相关阅读:
    Kubernetes1.91(K8s)安装部署过程(一)--证书安装
    开源仓库Harbor搭建及配置过程
    有关centos7 图形化root用户登录
    linux服务器查看tcp链接shell
    django表格form无法保存评论排查步骤
    Redis 4.x 安装及 发布/订阅实践和数据持久化设置
    django博客项目-设置django为中文语言
    windows 环境下如何使用virtualenv python环境管理工具
    【转载】python中利用smtplib发送邮件的3中方式 普通/ssl/tls
    php安装phpize工具
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3400376.html
Copyright © 2011-2022 走看看