https://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
我下載的是vertion2.2
開發Web等網絡應用程序的時候,需要確認網絡環境,連接情況等信息。如果沒有處理它們,是不會通過Apple的審查的。
Apple 的 例程Reachability中介紹了取得/檢測網絡狀態的方法。
在你的程序中使用
1、Reachability 只須將該例程中的 Reachability.h 和 Reachability.m 拷貝到你的工程中; 2、然後將 SystemConfiguration.framework 添加進工程。
Reachability 中定義了3種網絡狀態。
typedefenum {
NotReachable = 0,//無連接
ReachableViaWiFi,//使用3G/GPRS網絡
ReachableViaWWAN//使用WiFi網絡
} NetworkStatus;
簡單判斷項目連接:
// 是否wifi
+ (BOOL) IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否網絡連接
+ (BOOL) IsEnableConnection{
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
// 是否網絡連接
+ (BOOL) IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] ==ReachableViaWWAN);
}
下面是監聽整個項目網絡例子:
Java代碼/* File:ReachabilityAppDelegate.m Abstract:Theapplication'scontroller. Version:2.2 Disclaimer:IMPORTANT:ThisApplesoftwareissuppliedtoyoubyAppleInc. ("Apple")inconsiderationofyouragreementtothefollowingterms,andyour use,installation,modificationorredistributionofthisApplesoftware constitutesacceptanceoftheseterms.Ifyoudonotagreewiththeseterms, pleasedonotuse,install,modifyorredistributethisApplesoftware. Inconsiderationofyouragreementtoabidebythefollowingterms,andsubject totheseterms,Applegrantsyouapersonal,non-exclusivelicense,under Apple'scopyrightsinthisoriginalApplesoftware(the"AppleSoftware"),to use,reproduce,modifyandredistributetheAppleSoftware,withorwithout modifications,insourceand/orbinaryforms;providedthatifyouredistribute theAppleSoftwareinitsentiretyandwithoutmodifications,youmustretain thisnoticeandthefollowingtextanddisclaimersinallsuchredistributions oftheAppleSoftware. Neitherthename,trademarks,servicemarksorlogosofAppleInc.maybeused toendorseorpromoteproductsderivedfromtheAppleSoftwarewithoutspecific priorwrittenpermissionfromApple.Exceptasexpresslystatedinthisnotice, nootherrightsorlicenses,expressorimplied,aregrantedbyAppleherein, includingbutnotlimitedtoanypatentrightsthatmaybeinfringedbyyour derivativeworksorbyotherworksinwhichtheAppleSoftwaremaybe incorporated. TheAppleSoftwareisprovidedbyAppleonan"ASIS"basis.APPLEMAKESNO WARRANTIES,EXPRESSORIMPLIED,INCLUDINGWITHOUTLIMITATIONTHEIMPLIED WARRANTIESOFNON-INFRINGEMENT,MERCHANTABILITYANDFITNESSFORAPARTICULAR PURPOSE,REGARDINGTHEAPPLESOFTWAREORITSUSEANDOPERATIONALONEORIN COMBINATIONWITHYOURPRODUCTS. INNOEVENTSHALLAPPLEBELIABLEFORANYSPECIAL,INDIRECT,INCIDENTALOR CONSEQUENTIALDAMAGES(INCLUDING,BUTNOTLIMITEDTO,PROCUREMENTOFSUBSTITUTE GOODSORSERVICES;LOSSOFUSE,DATA,ORPROFITS;ORBUSINESSINTERRUPTION) ARISINGINANYWAYOUTOFTHEUSE,REPRODUCTION,MODIFICATIONAND/OR DISTRIBUTIONOFTHEAPPLESOFTWARE,HOWEVERCAUSEDANDWHETHERUNDERTHEORYOF CONTRACT,TORT(INCLUDINGNEGLIGENCE),STRICTLIABILITYOROTHERWISE,EVENIF APPLEHASBEENADVISEDOFTHEPOSSIBILITYOFSUCHDAMAGE. Copyright(C)2010AppleInc.AllRightsReserved. */ #import"ReachabilityAppDelegate.h" #import"Reachability.h" @implementationReachabilityAppDelegate -(void)configureTextField:(UITextField*)textFieldimageView:(UIImageView*)imageViewreachability:(Reachability*)curReach { NetworkStatusnetStatus=[curReachcurrentReachabilityStatus]; BOOLconnectionRequired=[curReachconnectionRequired]; NSString*statusString=@""; switch(netStatus) { caseNotReachable: { statusString=@"AccessNotAvailable"; imageView.image=[UIImageimageNamed:@"stop-32.png"]; //Minorinterfacedetail-connectionRequiredmayreturnyes,evenwhenthehostisunreachable.Wecoverthatuphere... connectionRequired=NO; break; } caseReachableViaWWAN: { statusString=@"ReachableWWAN"; imageView.image=[UIImageimageNamed:@"WWAN5.png"]; break; } caseReachableViaWiFi: { statusString=@"ReachableWiFi"; imageView.image=[UIImageimageNamed:@"Airport.png"]; break; } } if(connectionRequired) { statusString=[NSStringstringWithFormat:@"%@,ConnectionRequired",statusString]; } textField.text=statusString; } -(void)updateInterfaceWithReachability:(Reachability*)curReach { if(curReach==hostReach) { [selfconfigureTextField:remoteHostStatusFieldimageView:remoteHostIconreachability:curReach]; NetworkStatusnetStatus=[curReachcurrentReachabilityStatus]; BOOLconnectionRequired=[curReachconnectionRequired]; summaryLabel.hidden=(netStatus!=ReachableViaWWAN); NSString*baseLabel=@""; if(connectionRequired) { baseLabel=@"Cellulardatanetworkisavailable.\nInternettrafficwillberoutedthroughitafteraconnectionisestablished."; } else { baseLabel=@"Cellulardatanetworkisactive.\nInternettrafficwillberoutedthroughit."; } summaryLabel.text=baseLabel; } if(curReach==internetReach) { [selfconfigureTextField:internetConnectionStatusFieldimageView:internetConnectionIconreachability:curReach]; } if(curReach==wifiReach) { [selfconfigureTextField:localWiFiConnectionStatusFieldimageView:localWiFiConnectionIconreachability:curReach]; } } //CalledbyReachabilitywheneverstatuschanges. -(void)reachabilityChanged:(NSNotification*)note { Reachability*curReach=[noteobject]; NSParameterAssert([curReachisKindOfClass:[Reachabilityclass]]); [selfupdateInterfaceWithReachability:curReach]; } -(void)applicationDidFinishLaunching:(UIApplication*)application { #pragmaunused(application) contentView.backgroundColor=[UIColorgroupTableViewBackgroundColor]; summaryLabel.hidden=YES; //ObservethekNetworkReachabilityChangedNotification.Whenthatnotificationisposted,the //method"reachabilityChanged"willbecalled. [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(reachabilityChanged:)name:kReachabilityChangedNotificationobject:nil]; //Changethehostnameheretochangetheserveryourmonitoring remoteHostLabel.text=[NSStringstringWithFormat:@"RemoteHost:%@",@"www.apple.com"]; hostReach=[[ReachabilityreachabilityWithHostName:@"www.apple.com"]retain]; [hostReachstartNotifier]; [selfupdateInterfaceWithReachability:hostReach]; internetReach=[[ReachabilityreachabilityForInternetConnection]retain]; [internetReachstartNotifier]; [selfupdateInterfaceWithReachability:internetReach]; wifiReach=[[ReachabilityreachabilityForLocalWiFi]retain]; [wifiReachstartNotifier]; [selfupdateInterfaceWithReachability:wifiReach]; [windowmakeKeyAndVisible]; } @end
/* File: ReachabilityAppDelegate.m Abstract: The application's controller. Version: 2.2 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2010 Apple Inc. All Rights Reserved. */ #import "ReachabilityAppDelegate.h" #import "Reachability.h" @implementation ReachabilityAppDelegate - (void) configureTextField: (UITextField*) textField imageView: (UIImageView*) imageView reachability: (Reachability*) curReach { NetworkStatus netStatus = [curReach currentReachabilityStatus]; BOOL connectionRequired= [curReach connectionRequired]; NSString* statusString= @""; switch (netStatus) { case NotReachable: { statusString = @"Access Not Available"; imageView.image = [UIImage imageNamed: @"stop-32.png"] ; //Minor interface detail- connectionRequired may return yes, even when the host is unreachable. We cover that up here... connectionRequired= NO; break; } case ReachableViaWWAN: { statusString = @"Reachable WWAN"; imageView.image = [UIImage imageNamed: @"WWAN5.png"]; break; } case ReachableViaWiFi: { statusString= @"Reachable WiFi"; imageView.image = [UIImage imageNamed: @"Airport.png"]; break; } } if(connectionRequired) { statusString= [NSString stringWithFormat: @"%@, Connection Required", statusString]; } textField.text= statusString; } - (void) updateInterfaceWithReachability: (Reachability*) curReach { if(curReach == hostReach) { [self configureTextField: remoteHostStatusField imageView: remoteHostIcon reachability: curReach]; NetworkStatus netStatus = [curReach currentReachabilityStatus]; BOOL connectionRequired= [curReach connectionRequired]; summaryLabel.hidden =(netStatus != ReachableViaWWAN); NSString* baseLabel= @""; if(connectionRequired) { baseLabel= @"Cellular data network is available.\n Internet traffic will be routed through it after a connection is established."; } else { baseLabel= @"Cellular data network is active.\n Internet traffic will be routed through it."; } summaryLabel.text= baseLabel; } if(curReach == internetReach) { [self configureTextField: internetConnectionStatusField imageView: internetConnectionIcon reachability: curReach]; } if(curReach == wifiReach) { [self configureTextField: localWiFiConnectionStatusField imageView: localWiFiConnectionIcon reachability: curReach]; } } //Called by Reachability whenever status changes. - (void) reachabilityChanged: (NSNotification* )note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); [self updateInterfaceWithReachability: curReach]; } - (void) applicationDidFinishLaunching: (UIApplication* )application { #pragma unused(application) contentView.backgroundColor = [UIColor groupTableViewBackgroundColor]; summaryLabel.hidden = YES; // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the // method "reachabilityChanged" will be called. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; //Change the host name here to change the server your monitoring remoteHostLabel.text = [NSString stringWithFormat: @"Remote Host: %@", @"www.apple.com"]; hostReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain]; [hostReach startNotifier]; [self updateInterfaceWithReachability: hostReach]; internetReach = [[Reachability reachabilityForInternetConnection] retain]; [internetReach startNotifier]; [self updateInterfaceWithReachability: internetReach]; wifiReach = [[Reachability reachabilityForLocalWiFi] retain]; [wifiReach startNotifier]; [self updateInterfaceWithReachability: wifiReach]; [window makeKeyAndVisible]; } @end