zoukankan      html  css  js  c++  java
  • iPhone 网络连接检测(Wifi,3G,Edge),功能有点像Reachability(转)

    这个类可以用来检测用户是否连接到internet.  用法非常简单,只有一个方法,返回 YES或NO。

    一个简单的例子:

    if ([Connection isConnected]) {  ...  }     
    else {  ...  }  
    

    类的头文件

    //   
    //  Connection.h     
    //   
    #import <Foundation/Foundation.h>   
    #import <SystemConfiguration/SystemConfiguration.h>   
    #import <netinet/in.h>   
    #import <arpa/inet.h>   
    #import <netdb.h>   
      
    @interface Connection : NSObject {   
    }   
      
    + (BOOL) isConnected;   
      
    @end 
    

    类的实现文件

    //   
    //  Connection.m  
    //     
    #import "Connection.h"   
      
    @implementation Connection   
      
    + (BOOL) isConnected {   
        // Create zero addy   
        struct sockaddr_in zeroAddress;   
        bzero(&zeroAddress, sizeof(zeroAddress));   
        zeroAddress.sin_len = sizeof(zeroAddress);   
        zeroAddress.sin_family = AF_INET;   
        // Recover reachability flags   
        SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);   
        SCNetworkReachabilityFlags flags;   
        BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);   
        CFRelease(defaultRouteReachability);   
        if (!didRetrieveFlags) {   
            NSLog(@"Error. Could not recover network reachability flags");   
            return NO;   
        }   
        BOOL isReachable = flags & kSCNetworkFlagsReachable;   
        BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;   
        BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;   
        NSURL *testURL = [NSURL URLWithString:@"http://www.google.com/"];   
        NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];   
        NSURLConnection *testConnection = [[[NSURLConnection alloc] initWithRequest:testRequest delegate:self] autorelease];   
        return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;   
    }   
    
    @end  
    

    最后别忘了添加必要的frameworks: SystemConfiguration and libz.1.1.3.dylib

    标题中提到的Reachability也具有检测网络的功能。大家可以参考资料:http://www.raddonline.com/blogs/geek-journal/iphone-sdk-testing-network-reachability/

    http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

  • 相关阅读:
    pycharm使用技巧
    for 循环
    面向对象进阶
    python实现socket上传下载文件-进度条显示
    python实现进度条--主要用在上传下载文件
    django下常用查询的API
    django下model.py模型的定义
    django下数据库配置
    ORM机制简介
    views.py文件详解
  • 原文地址:https://www.cnblogs.com/peer/p/2043892.html
Copyright © 2011-2022 走看看