網頁

2012年5月31日 星期四

網路檢測

20120613新增apple官網範例(使用方式略有差異)

【環境:xCode4.2 , ios5.1】
宣告:利用 UIDevice 的功能
說明:
Connectivity(.h .m)資料來源參考-掌握iPhone SDK 程式開發技巧
利用該原碼提供網路偵測的判斷,使用前須先挂載 SystemConfiguration.framework,挂載方式請參閱
引用方式[UIDevice cellularConnected][UIDevice wiFiConnected][UIDevice networkConnected]即可使用

功能執行:
1.利用淡入淡出視覺頁面


2.切換進入功能頁,點選按鈕可偵測網路....啓動語音或者視訊等相關功能



範例下載

<以下範例>
Connectivity.h
 
#import <SystemConfiguration/SCNetworkReachability.h>

//add SystemConfiguration Framework

@interface UIDevice (DeviceConnectivity)

+(BOOL)cellularConnected; 
+(BOOL)wiFiConnected;
+(BOOL)networkConnected;   

@end
Connectivity.m
#import "Connectivity.h"

#define EXTERNAL_HOST @"google.com"

@implementation UIDevice (DeviceConnectivity)

+(BOOL)cellularConnected{// EDGE or GPRS
  SCNetworkReachabilityFlags    flags = 0;
  SCNetworkReachabilityRef      netReachability = NULL;  
  netReachability     = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [EXTERNAL_HOST UTF8String]);
  if(netReachability){
    SCNetworkReachabilityGetFlags(netReachability, &flags);
    CFRelease(netReachability);
  }
  if(flags & kSCNetworkReachabilityFlagsIsWWAN){
    return YES;
  }
  return NO;
}
+(BOOL)wiFiConnected{
  if([self cellularConnected]){
    return NO;
  }
  return [self networkConnected];
}
+(BOOL)networkConnected{
  SCNetworkReachabilityFlags     flags = 0;
  SCNetworkReachabilityRef       netReachability = NULL;
  BOOL                           retrievedFlags = NO;
  
  netReachability     = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [EXTERNAL_HOST UTF8String]);
  if(netReachability){
    retrievedFlags      = SCNetworkReachabilityGetFlags(netReachability, &flags);
    CFRelease(netReachability);
  }
  if (!retrievedFlags || !flags){
    return NO;
  }
  return YES;
}
@end

沒有留言:

張貼留言