最近在開始學習寫IPhone軟體, 判斷網路連線部分, 參考過官方sample code Reachability,在xcode4.2上面由於我原本專案有使用了Apple LLVM compiler 3.0, 所以在調用官方sample code時設定一直有問題, 爬過Google後有發現有其他方式可以判斷, 參考網址轉載如下:http://blog.csdn.net/favormm/article/details/5352656
開發環境 Mac OS X 10.6.8, Xcode 4.2 首先,
添加framework (SystemConfiguration, libz.1.1.3.dylib)至專案
接下來新增檔案(command + n), 選擇Cocoa Touch -> Objective-C class -> NSObject -> 檔案名稱(這裡將檔案名稱命名為Connect), 接下來在Connect.h中, 修改程式碼如下
Connect.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
Connect.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];
//[[[NSURLConnection alloc] initWithRequest:testRequest delegate:self] autorelease]; return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO; }
@end
接下來在欲調用此程式function, 記得 #import “Connection.h" 並且在調用的地方撰寫如下
ex: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization if ([Connection isConnected]) {...} else{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"連線錯誤" message:@"無法連結網路! 請關閉飛航模式或至設定確認您已開啟Wi-Fi或是行動網路。" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertView show]; return nil; } return self; }