Sni*_*der 14 cocoa-touch objective-c reachability ios
我想知道如何检查用户是通过WIFI还是蜂窝数据3G或4G连接到互联网.
此外,我不想检查网站是否可访问,我想检查设备上是否有互联网.我试图查看互联网所有我看到的是他们检查网站是否可以访问或不使用Rechability该类.
我想在打开我的应用程序时检查用户是否有互联网.
我正在使用带有Objective-C的Xcode6.
Jay*_*ani 21
使用此代码并导入Reachability.h文件
if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
{
//connection unavailable
}
else
{
//connection available
}
Run Code Online (Sandbox Code Playgroud)
首先从此链接下载Reachability类:
Github的可更新性
在AppDelegate.h中添加可达性实例
@property (nonatomic) Reachability *hostReachability;
@property (nonatomic) Reachability *internetReachability;
@property (nonatomic) Reachability *wifiReachability;
Run Code Online (Sandbox Code Playgroud)
在AppDelegate中导入可达性,只需在Appdelegate.m中复制并通过此代码即可
- (id)init
{
self = [super init];
if (self != nil)
{
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
NSString *remoteHostName = @"www.google.com";
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[self.hostReachability startNotifier];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
self.wifiReachability = [Reachability reachabilityForLocalWiFi];
[self.wifiReachability startNotifier];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
在Common Class中添加此方法.
/*================================================================================================
Check Internet Rechability
=================================================================================================*/
+(BOOL)checkIfInternetIsAvailable
{
BOOL reachable = NO;
NetworkStatus netStatus = [APP_DELEGATE1.internetReachability currentReachabilityStatus];
if(netStatus == ReachableViaWWAN || netStatus == ReachableViaWiFi)
{
reachable = YES;
}
else
{
reachable = NO;
}
return reachable;
}
Run Code Online (Sandbox Code Playgroud)
请注意,APP_DELEGATE1是AppDelegate的实例
/* AppDelegate object */
#define APP_DELEGATE1 ((AppDelegate*)[[UIApplication sharedApplication] delegate])
Run Code Online (Sandbox Code Playgroud)
您可以使用此方法在应用中的任何位置检查互联网连接
| 归档时间: |
|
| 查看次数: |
38750 次 |
| 最近记录: |