iOS判断手机是否联网AFNetworking以及SystemConfiguration.framework

1、AFNetworking

找到这个判断网络的第三方框架,导入到项目中,在需要判断网络状态的Controller中导入

#import "AFNetworkReachabilityManager.h"

    AFNetworkReachabilityManager *managerAF = [AFNetworkReachabilityManager sharedManager];
    //    开始监测网络
    [managerAF startMonitoring];
    //    网络状态发生改变时 调用
    [managerAF setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [self showAlertWithMessage:@"暂时没有网络,请检查网络"];
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                [self showAlertWithMessage:@"暂时没有网络,请检查网络"];
                
                break;
    
            default:
                break;
        }
    }];

2、SystemConfiguration.framework

在项目中导入SystemConfiguration.framework框架。在需要判断网络状态的Controller中导入

#import

    BOOL flag = [self connectedToNetwork];
    if (!flag) {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"网络提示" message:@"网络未连接" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
#pragma mark 判断手机是否联网
- (BOOL)connectedToNetwork{
    
    //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
    
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    // Recover reachability flags
    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;
}



你可能感兴趣的:(iOS开发小技巧)