0

For my current sprite kit game that is coded in OBJECTIVE - C, I want to check for internet connection before providing the user with an option to view an incentivized ad. How would I do this? I only want the option to appear if the user is connected to the internet.

d33
  • 17
  • 3

1 Answers1

1

Step-1) Download the Reachability project from GitHub Project from here.

Step-2) Add Reachability.h and Reachability.m files in your project from github project.

Step-3) In your viewController.m -> #import "Reachability.h" add below code in your viewController.m

#define KWebURL  @"http://yourWebservicesbaseURl_or_hostName"

-(BOOL)isConnected{
     Reachability *aReachability = [Reachability reachabilityWithHostName:your_Server_MainURL];

    NetworkStatus netStatus = [aReachability currentReachabilityStatus];

    if(netStatus==0)
    {
        return NO;
    }
    else if(netStatus==1)
    {
        return YES;
    }
    else if(netStatus==2)
    {
    return YES;
    }
    else
    {
        return YES;
    }
}

Step-4) Uses: now check conectivity using below code in your ViewDidload or where you have to impliment.

if ([self isConnected]) {
    // your internet is connected.
}else{
    // your internet is not connected.
}

-- OR --

if you have to make one global Object Class to use it globally from anywhere then floow from Step-3) like....

Step-3.0) First make New NSObject Class i.e Webservice.h and Webservice.m

Step-3.1) In your Webservice.h -->

#import <Foundation/Foundation.h>
#import "Reachability.h"

@interface Webservice : NSObject

+(BOOL)isConnected;

@end

Step-3.2) In your Webservice.m -->

#import "Webservice.h"
#import "Reachability.h"

@implementation Webservice
+(BOOL)isConnected
{
    Reachability *aReachability = [Reachability reachabilityWithHostName:your_Server_MainURL];
    NetworkStatus netStatus = [aReachability currentReachabilityStatus];

    if(netStatus==0)
    {
        return NO;
    }
    else if(netStatus==1)
    {
    return YES;
    } 
    else if(netStatus==2)
    {
        return YES;
    }
    else
    {
        return YES;
    }
}

@end

Step-4) Uses: now check conectivity using below code in your any viewControllers or anywhere you have to impliment.

if ([Webservice isConnected]) {
    // your internet is connected.
}else{
    // your internet is not connected.
}
Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
Vvk
  • 4,031
  • 29
  • 51
  • I'm pretty sure this example is wrong, the `reachabilityWithHostName` doesn't tell you if you have a connection, you have to set up some code blocks that get called as the connection status changes. There is an example in that GitHub project. – Flexicoder Jan 23 '16 at 14:46