要在 iOS 上判斷網路是否可用,最基礎的做法是 SystemConfiguration 框架裡的 SCNetworkReachability。使用前記得先把 SystemConfiguration.framework 加入專案。
#import <UIKit/UIKit.h> @interface ViewController : UIViewController // 如果方法前面加上 +,就是類的靜態方法,這裡先寫成實例方法 - (BOOL)connectedToNetwork; @end
#import "ViewController.h"
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonHMAC.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netdb.h>
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [[UIButton alloc] init];
btn.frame = CGRectMake(20, 20, 40, 40);
btn.backgroundColor = [UIColor brownColor];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(testOut:) forControlEvents:UIControlEventTouchUpInside];
}
- (BOOL)connectedToNetwork {
// 建立 zero address 結構
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// 取得 reachability flags
SCNetworkReachabilityRef defaultRouteReachability =
SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
printf("Error. Could not recover network reachability flags\n");
return NO;
}
BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
return (isReachable && !needsConnection) ? YES : NO;
}
// 在按鈕事件中使用
- (IBAction)testOut:(UIButton *)sender {
if (![self connectedToNetwork]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示"
message:@"網絡連接失敗,請查看網絡是否連接正常!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
NSLog(@"testOut Event");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
Reachability 只能告訴你「有沒有可用的路由」,並不代表網路真的通。基地台訊號存在但沒有實際連線、或是連上 Wi-Fi 卻沒有對外網路(常見的需登入 Portal),它仍會回報可達。因此正式專案應該搭配實際的請求逾時處理,把 Reachability 當作「提前提示」而非唯一依據。
另外,Reachability 有現成的匿名函式版本 API,能註冊通知在網路狀態變動時主動 callback,比每次操作前都去查一次更省資源。若使用 Swift,Apple 也已提供更新版的 NWPathMonitor 作為替代方案。