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(@"网络请求完成");
    
 }

转载于:https://www.cnblogs.com/PSSSCode/p/5292886.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值