en

hi, it seems you are using microsoft internet explorer. it doesn't match web standard and causes problems browsing this site. please please please use mozilla firefox or google chrome instead. thank you!

zh

哦哦!您正在使用Internet Explorer 瀏覽器,它與我們的網頁標準並不相容,可能會導致畫面顯示不正常。
請改用 Mozilla Firefox 或者 Google Chrome 才能正常瀏覽本網站,謝謝!

12.31.2010

利用 SCNetworkReachability 取得網路服務狀態的方法

 

若要辨識網路的服務狀態,可以參考以下程式碼範例。

在開始之前首先要 import 兩個標頭檔並加入 SystemConfiguration.framework,加入的方法是在 Groups & Files 內的專案名稱上按下右鍵 > Add > Existing Frameworks,之後選擇需要的 framework 並 Add 即可。


#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>


//Create zero addy
struct sockaddr_in Addr;
bzero(&Addr, sizeof(Addr));
Addr.sin_len = sizeof(Addr);
Addr.sin_family = AF_INET;

//結果存至旗標中
SCNetworkReachabilityRef target = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *) &Addr);
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(target, &flags);


//將取得結果與狀態旗標位元做AND的運算並輸出
if (flags & kSCNetworkFlagsReachable) switch1.on = YES; else switch1.on = NO;
if (flags & kSCNetworkReachabilityFlagsIsWWAN) switch2.on = YES; else switch2.on = NO;

如果讀者有興趣,也可是著參考下列 iOS Library 的提供的旗標判斷。

(flags & kSCNetworkReachabilityFlagsIsWWAN)
(flags & kSCNetworkReachabilityFlagsReachable)

(flags & kSCNetworkReachabilityFlagsTransientConnection)
(flags & kSCNetworkReachabilityFlagsConnectionRequired)
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)
(flags & kSCNetworkReachabilityFlagsInterventionRequired)
(flags & kSCNetworkReachabilityFlagsConnectionOnDemand)
(flags & kSCNetworkReachabilityFlagsIsLocalAddress)
(flags & kSCNetworkReachabilityFlagsIsDirect)






沒有留言:

張貼留言