zoukankan      html  css  js  c++  java
  • AFN检測网络情况


    问:

    I'm a bit lost on AFNetorking's Reachability and haven't found a lot of good information out there.

    I have an app that logs into a web API. Each VC connects to the API in some way so each VC needs to have network access. I use a subclass of AFHTTPSessionManager to make network requests.

    I am confused as to where to put the code - is it just the appDelegate or is it in each VC?

    What is the use of this code?

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];

    And where do you use these methods and how do they relate to the code above?

    -startMonitoring
    -stopMonitoring


    答:

    The -startMonitoring method of AFNetworking is used to make your AFNetworkReachabilityManager start monitoring the network connection. If you do not call -startMonitoring, your setReachabilityStatusChangeBlock will never be called (regardless of where you put it) since AFNetworking isn't monitoring your connection.

    As you probably assumed, -stopMonitoring does the exact opposite of -startMonitoring - it stops the manager from checking network connectivity. I normally don't use this method in my apps, but if your app doesn't need a network connection for a certain part of it, feel free to call it (just make sure you start monitoring the network again when you need to).

    The setReachabilityStatusChangeBlock is called whenever the network status changes. You can put this wherever you want to make changes if/when the network changes. An example of this would be putting it in your app delegate and sending out a NSNotification when the network status changes so that any view controller observing the notification can react appropriately.

    You can also manually check to see if the network is online (as long as -startMonitoring was called and AFNetworking is monitoring your network) using something like this:

    if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
        NSLog(@"Online");
    }

    You can read more on AFNetworking's official documentation on GitHub.


  • 相关阅读:
    CentOS7.4 + Ambari 2.6.1.5 + HDP 2.6.4.0 安装部署
    分布式业务的异常解决思路
    RPC簡介
    网络I/O模型--07Netty基础
    网络I/O模型--06异步I/O
    网络I/O模型--05多路复用I/O
    网络I/O模型--04非阻塞模式(解除accept()、 read()方法阻塞)的基础上加入多线程技术
    网络I/O模型--03非阻塞模式(ServerSocket与Socket的超时处理)--解除accept()、 read()方法阻塞
    网络I/O模型--02阻塞模式(多线程)
    Android开发(五)——计时器
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/7256919.html
Copyright © 2011-2022 走看看