Reputation: 6275
I've to get notified when the device lost or obtain connection and I have to show an alert "Device is going offline" or "Device is going online" It's possible ?
Thanks.
Upvotes: 0
Views: 80
Reputation: 82759
use Reachability , the apple provide the default function for get the network status , try the following link , in here you get the sample code also
choice no-2
the following tutorial helps you for do the work in step by step and you can get the status also
choice no --3
create the custom NSObject
class and follow the details
#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 file
#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
accessing like
if(![OUTTDeviceUtility connectedToNetwork] && ![OUTTDeviceUtility connectedToWiFi])
{
// do your stuff
}
else
{
// show the error
}
Upvotes: 1