• iOS中的网络请求 和 网络监测


    1、网络监测

    
        //根据主机名判断网络是否连接
    
        Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"]; 
    
        self.reach = reach;
    
        //注册网络监听通知
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];
    
        //开启监听
    
        [reach startNotifier];
    
       //根据currentReachabilityStatus判断网络状态
    
    NotReachable = 0, //没有网络
    ReachableViaWiFi = 2, //不用花钱WIFI
    ReachableViaWWAN = 1 //2G,3G,4G
    - (void)dealloc {
        
        //把当前的对象所有通知删除
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    
        //停止监听
        [self.reach stopNotifier];
    }
    

    2、异步网络请求

    //1、创建URL,访问网络资源的唯一地址
    
        NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/demo.json"];
    
    //2、创建网络请求
    
        /*
    
         cachePolicy 缓存策略
    
         NSURLRequestUseProtocolCachePolicy = 0, //自动缓存策略
    
         NSURLRequestReloadIgnoringLocalCacheData = 1, //每次都请求网络,无论本地是否存在缓存
    
         NSURLRequestReturnCacheDataElseLoad = 2,//如果有缓存返回缓存,没有就加载网络
    
         NSURLRequestReturnCacheDataDontLoad = 3,//如果有缓存返回缓存,没有也不加载网络
    
         timeoutInterval 请求超时 默认超时时间是60 一般设置 10 - 20s     
    
         */    
    
    
    
        NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    
    
    //3、建立连接
    //sendAsynchronousRequest 建立异步网络连接
    
    //queue  可以传主队列,或全局队列
    
    //[NSOperationQueue mainQueue]   不用调到主队列直接更新
    
    //[[NSOperationQueue alloc] init]  则需要调回主线程更新UI
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    
        //response 服务器响应信息,一般下载时有用
    
        //data  服务器返回的数据
    
        //connectionError 网络请求错误
    
        
    
        //服务器与客户端是以二进制流通讯的
    
        
    
        NSLog(@"%@",data);
    
        
    
        [data writeToFile:@"/Users/dahuan/Desktop/test" atomically:YES];
    
        
    
        NSLog(@"%@",[NSThread currentThread]);
    
        
    
        if (connectionError) {
    
            
    
            NSLog(@"错误信息:%@",connectionError);
    
            
    
        } else {
    
            
    
            NSLog(@"响应信息:%@",response);
    
            
    
            NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
            
    
            NSLog(@"%@",string);
    
            
    
            [self.webView loadHTMLString:string baseURL:nil];
    
        }
    
    
    
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    
            //更新UI
    
        }];
    
    }];
    

    3、同步网络请求

        NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/demo.json"];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        
        //同步网络请求
        
        NSURLResponse * response = nil;
        NSError * error = nil;
        
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        
        NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
        NSLog(@"%@",string);
        NSLog(@"%@",response);
    

    4、NSURLConnection代理方法

        self.data = [NSMutableData data];
        
        NSString * urlString = @"http://192.168.1.123/把悲伤留给自己.mp3";
        
        //NSString 中包含中文字符时转换为NSURL
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSURL * url = [NSURL URLWithString:urlString];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        
        NSURLConnection * connect = [NSURLConnection connectionWithRequest:request delegate:self];
        
        //开启网络连接
        [connect start];
    
    
    //服务器返回响应信息1
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
            
        NSLog(@"%@",response);
        
    }
    
    //接受数据(多次调用)2
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        
        [self.data appendData:data];
        
        NSLog(@"%@",data);
        
    }
    
    //请求完成3
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
        
        [self.data writeToFile:@"/Users/dahuan/Desktop/aaaaa.mp3" atomically:YES];
        NSLog(@"网络请求完成");
        
     }
    
  • 相关阅读:
    大二下每周总结
    大二下学期阅读笔记(人月神话)
    大二下学期第一次结对作业(第二阶段)
    大二下学期第一次结对作业(第二阶段)
    大二下学期项目练习(滑屏数据展示)
    elasticSearch中使用聚合查询后只显示10个bucket的问题
    elasticsearch Terms Query 实现类似于sql in查询
    crontab定时调用shell脚本
    java使用static静态变量
    ElasticSearch 复合数据类型——数组,对象和嵌套
  • 原文地址:https://www.cnblogs.com/PSSSCode/p/5292886.html
Copyright © 2020-2023  润新知