iOS在设备丢失/获取连接时收到通知

时间:2015-07-27 10:07:53

标签: ios objective-c

我在设备丢失或获得连接时收到通知我必须显示警告"设备正在脱机"或"设备正在上线" 它有可能吗?

感谢。

1 个答案:

答案 0 :(得分:1)

使用 Reachability ,苹果提供了获取网络状态的默认功能,请尝试以下link ,在这里您也可以获得示例代码

选择no-2

以下tutorial可帮助您逐步完成工作,并且您也可以获得状态

选择否 - 3

创建自定义NSObject课程并按照详细信息

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SCNetworkReachability.h>


typedef enum {
IOSDeviceTypeIphone          = 1,
IOSDeviceTypeIpad            = 2,
IOSDeviceTypeIpodTouch       = 3,
} IOSDeviceType;


@interface OUTTDeviceUtility : NSObject

+(id) sharedInstance;

+ (BOOL)checkConnection:(SCNetworkReachabilityFlags*)flags;
+ (BOOL)connectedToNetwork;
+ (BOOL)connectedToWiFi;
@end

.m文件

#import "OUTTDeviceUtility.h"
#import <sys/types.h>
#import <sys/socket.h>
#import <sys/sysctl.h>
#import <sys/time.h>
#import <netinet/in.h>
#import <net/if_dl.h>
#import <netdb.h>
#import <errno.h>
#import <arpa/inet.h>
#import <unistd.h>
#import <ifaddrs.h>

@implementation OUTTDeviceUtility

+(id)sharedInstance{
static OUTTDeviceUtility* deviceUtilInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    deviceUtilInstance = [[OUTTDeviceUtility alloc] init];
});

return deviceUtilInstance;
}

+ (BOOL)checkConnection:(SCNetworkReachabilityFlags*)flags
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, flags);
CFRelease(defaultRouteReachability);

if(!didRetrieveFlags)
    return NO;
return YES;
}

 + (BOOL)connectedToNetwork
{
SCNetworkReachabilityFlags flags;
if(![OUTTDeviceUtility checkConnection:&flags])
    return NO;

BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;
BOOL needsConnection = flags & kSCNetworkReachabilityFlagsConnectionRequired;

return (isReachable && !needsConnection) ? YES : NO;
}

+ (BOOL)connectedToWiFi
{
SCNetworkReachabilityFlags flags;
if(![OUTTDeviceUtility checkConnection:&flags])
    return NO;

BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;
BOOL needsConnection = flags & kSCNetworkReachabilityFlagsConnectionRequired;
BOOL cellConnected = flags & kSCNetworkReachabilityFlagsTransientConnection;

return (isReachable && !needsConnection && !cellConnected) ? YES : NO;
}

@end

访问

 if(![OUTTDeviceUtility connectedToNetwork] && ![OUTTDeviceUtility connectedToWiFi])
{

 // do your stuff

}
else
{
  // show the error
 }