IOS

IOS TutorialAirPrint tutorial in iOSCarthage iOS SetupChecking iOS versionCore SpotLight in iOSCreate a Custom framework in iOSDeep Linking in iOSExtension for rich Push Notification - iOS 10.Guideline to choose best iOS Architecture PatternsIOS - Implementation of XMPP with Robbie Hanson frameworkIOS 3D TouchIOS 10 Speech Recognition APIIOS AccessibilityIOS ADDING a SWIFT BRIDGING HEADERIOS AFNetworkingIOS AirDropIOS AlamofireIOS App Submission ProcessIOS App Transport Security (ATS)IOS App wide operationsIOS AppDelegateIOS Application rating/review requestIOS ARC (Automatic Reference Counting)IOS attributedText in UILabelIOS Auto LayoutIOS AVPlayer and AVPlayerViewControllerIOS AVSpeechSynthesizerIOS AWS SDKIOS Background ModesIOS Background Modes and EventsIOS Basic text file I/OIOS BlockIOS CAAnimationIOS Cache online imagesIOS CAGradientLayerIOS CALayerIOS CAShapeLayerIOS CategoriesIOS CGContext ReferenceIOS Chain Blocks in a Queue (with MKBlockQueue)IOS Change Status Bar ColorIOS Checking for Network ConnectivityIOS CLLocationIOS CloudKitIOS CodableIOS Code signingIOS ConcurrencyIOS Configure Beacons with CoreBluetoothIOS Contacts FrameworkIOS Content Hugging/Content Compression in AutoLayoutIOS Convert HTML to NSAttributed string and vice verseIOS Convert NSAttributedString to UIImageIOS Core DataIOS Core GraphicsIOS Core LocationIOS Core MotionIOS CoreImage FiltersIOS Create .ipa File to upload on appstore with ApplicationloaderIOS Create a video from imagesIOS Creating an App IDIOS CTCallCenterIOS Custom fontsIOS Custom KeyboardIOS Custom methods of selection of UITableViewCellsIOS Custom UITextFieldIOS Custom UIViews from XIB filesIOS Cut a UIImage into a circleIOS CydiaSubstrate tweakIOS Debugging CrashesIOS DispatchGroupIOS Dynamic TypeIOS Dynamically updating a UIStackViewIOS EventKitIOS Face Detection Using CoreImage/OpenCVIOS FacebookSDKIOS FastlaneIOS FCM Messaging in SwiftIOS FileHandleIOS GameCenter LeaderboardsIOS GameplayKitIOS GCD (Grand Central Dispatch)IOS Google Places APIIOS Graph (Coreplot)IOS Handle Multiple Environment using MacroIOS Handling URL SchemesIOS HealthkitIOS iBeaconIOS IBOutletsIOS In-App PurchaseIOS Initialization idioms



IOS Checking for Network Connectivity

From WikiOD

Remarks[edit | edit source]

The source code for Reachability.h and Reachability.m can be found on Apple's developer documentation site.

Caveats[edit | edit source]

Unlike other platforms, Apple is yet to provide a standard set of APIs to determine an iOS device's network status and offer only these code examples linked above. The source file change over time, but once imported into an app project, they are seldom updated by the developers.

For this reason most app developers tend to use one of the many Github/Cocoapod maintained libraries for reachability.

Apple also recommends, for requests made at the user’s behest, that you always attempt a connection first, before using Reachability/SCNetworkReachability to diagnose the failure or to wait for the connection to return.

Creating a Reachability listener[edit | edit source]

Apple's Reachability class periodically checks the network status and alerts observers to changes.

Reachability *internetReachability = [Reachability reachabilityForInternetConnection];
[internetReachability startNotifier];

Add observer to network changes[edit | edit source]

Reachability uses NSNotification messages to alert observers when the network state has changed. Your class will need to become an observer.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

Elsewhere in your class, implement method signature

* (void) reachabilityChanged:(NSNotification *)note {
    //code which reacts to network changes
}

Alert when network becomes unavailable[edit | edit source]

* (void)reachabilityChanged:(NSNotification *)note {
    Reachability* reachability = [note object];
    NetworkStatus netStatus = [reachability currentReachabilityStatus];

    if (netStatus == NotReachable) {
        NSLog(@"Network unavailable");
    }
}

Alert when connection becomes a WIFI or cellular network[edit | edit source]

* (void)reachabilityChanged:(NSNotification *)note {
    Reachability* reachability = [note object];
    NetworkStatus netStatus = [reachability currentReachabilityStatus];

    switch (netStatus) {
        case NotReachable:
            NSLog(@"Network unavailable");
            break;
        case ReachableViaWWAN:
            NSLog(@"Network is cellular");
            break;
        case ReachableViaWiFi:
            NSLog(@"Network is WIFI");
            break;
    }
}

Verify if is connected to network[edit | edit source]

Swift

import SystemConfiguration

/// Class helps to code reuse in handling internet network connections.
class NetworkHelper {

    /**
     Verify if the device is connected to internet network.
     - returns:          true if is connected to any internet network, false if is not
     connected to any internet network.
     */
   class func isConnectedToNetwork() -> Bool {
       var zeroAddress = sockaddr_in()

       zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
       zeroAddress.sin_family = sa_family_t(AF_INET)

       let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
           SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
       }

       var flags = SCNetworkReachabilityFlags()

       if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
           return false
       }

       let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
       let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

      return (isReachable && !needsConnection)
   }
}

if NetworkHelper.isConnectedToNetwork() {
    // Is connected to network
}

Objective-C:

we can check network connectivity within few lines of code as:

-(BOOL)isConntectedToNetwork
{
    Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
    if (networkStatus == NotReachable)
    {
        NSLog(@"There IS NO internet connection");
        return false;
    } else
    {
        NSLog(@"There IS internet connection");
        return true;
    }
}

Credit:Stack_Overflow_Documentation