若要辨識網路的服務狀態,可以參考以下程式碼範例。
在開始之前首先要 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)
沒有留言:
張貼留言