美文网首页
用SCNetworkReachability判断联网状态

用SCNetworkReachability判断联网状态

作者: ShineYangGod | 来源:发表于2018-02-26 15:11 被阅读27次

    1、判断手机是否连接到网络,iOS提供了一个SCNetworkReachabilityRef类,方便我们的使用。
    2、创建一个工具类,方便全局调用
    .h

    import <Foundation/Foundation.h>

    @interface NetworkUtil : NSObject

    • (BOOL)isNetworkReachable;

    @end

    .m

    import "NetworkUtil.h"

    import <SystemConfiguration/SCNetworkReachability.h>

    import <netdb.h>

    @implementation NetworkUtil

    // networkチェック

    • (BOOL)isNetworkReachable
      {
      // Create zero addy
      //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
      struct sockaddr_in zeroAddress;
      bzero(&zeroAddress, sizeof(zeroAddress));
      zeroAddress.sin_len = sizeof(zeroAddress);
      zeroAddress.sin_family = AF_INET;

      // Recover reachability flags
      // SCNetworkReachabilityFlags:保存返回的测试连接状态
      // 其中常用的状态有:
      // kSCNetworkReachabilityFlagsReachable:能够连接网络
      // kSCNetworkReachabilityFlagsConnectionRequired:能够连接网络,但是首先得建立连接过程
      // kSCNetworkReachabilityFlagsIsWWAN:判断是否通过蜂窝网覆盖的连接,比如EDGE,GPRS或者目前的3G.主要是区别通过WiFi的连接。
      SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL,
      (struct sockaddr*)&zeroAddress);
      SCNetworkReachabilityFlags flags;

      BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
      CFRelease(defaultRouteReachability);

      if (!didRetrieveFlags) {
      return NO;
      }

      BOOL isReachable = flags & kSCNetworkFlagsReachable;
      BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
      return (isReachable && !needsConnection) ? YES : NO;
      }

    @end

    使用

    import "ViewController.h"

    import "NetworkUtil.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    • (void)viewDidLoad {
      [super viewDidLoad];

      BOOL result = [NetworkUtil isNetworkReachable];

      NSLog(@"是否可以联网:%@",result?@"YES":@"NO");

    }

    @end

    相关文章

      网友评论

          本文标题:用SCNetworkReachability判断联网状态

          本文链接:https://www.haomeiwen.com/subject/iajyxftx.html