0

How can, I check internet connectivity.?

The below code just shows the connection to wifi or mobile network but cannot check current internet connectivity.

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}
Malik 007
  • 43
  • 6

7 Answers7

0

An exact answer is here Reachability.swift. All cool developers use this solution. You also can find an example and try handle it on your own (with your base url, design of your beheviour and etc).

Agisight
  • 1,778
  • 1
  • 14
  • 15
0

create a function like

public func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        SCNetworkReachabilityCreateWithAddress(nil, $0)
    }
}) else {
    return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
    return false
}
if flags.isEmpty {
    return false
}

let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}

then use it as boolean value

e.g if isConnectednetwork {}

hope this will solve you problems.

Hasnain ahmad
  • 301
  • 1
  • 10
  • 33
0

Here is full code for check network reachability.

https://drive.google.com/drive/folders/1VzH_ysuOaXts7c6KKXzgGDLOHkV6_8QR?usp=sharing

hope! this help you...

Khushal iOS
  • 303
  • 2
  • 12
0

Add Reachability.h and Reachability.m files in your swift project.

enter image description here

Create Bridging_Header

#ifndef xxx_Bridging_Header_h
#define xxx_Bridging_Header_h

#import "Reachability.h"

#endif /* xxx_Bridging_Header_h */

AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var isReachable: Reachability!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        self.isReachable = Reachability.forInternetConnection()
        NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(_:)), name: NSNotification.Name.reachabilityChanged,
                                               object: nil)
        self.isReachable!.startNotifier()
        return true
    }

    //Reachbality Notification Response
    @objc func reachabilityChanged(_ notification: Notification) {

        if self.isReachable.isReachableViaWiFi() || self.isReachable.isReachableViaWWAN() {
            print("Service avalaible!!!")
        } else {
            print("No service avalaible!!!")
        }
    }
}

Constants.swift

import Foundation
import UIKit

class Constants: NSObject {

    struct ReferenecVariables {
        static let appDelegate = UIApplication.shared.delegate as! AppDelegate
    }
}

Viewcontroller.swift

...

@IBAction func loginButtonClicked() {
   if Constants.ReferenecVariables.appDelegate.isReachable.isReachable() {
      //network available
   }else {
      //network not available.
  }
}
...


Or Another Answer


Add SystemConfiguration.framework enter image description here

import UIKit
import SystemConfiguration
....
....
@IBAction func signInButtonTapped(sender:AnyObject){
    let status:Bool = self.checkInternet()
    if status == false {
       //Network not available
    }else{
       // Network available
    }
}
func checkInternet() -> Bool{
    //CHECK INTERNET CONNECTION
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }
    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }
    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return isReachable && !(needsConnection)
}
Ramprasath Selvam
  • 3,868
  • 3
  • 25
  • 41
0

Use Alamofire library to check the device connected to the network or not.

import Foundation
import Alamofire

class Connectivity {
    class func isConnectedToInternet() ->Bool {
        return NetworkReachabilityManager()!.isReachable
    }
}

And add this to your code

if Connectivity.isConnectedToInternet() {
        print("Yes! internet is available.")
        // do some tasks..
 }
Ashish Rana
  • 121
  • 1
  • 1
  • 6
0

I use Reachability framework to check internet connection, here is my manager

import UIKit
import Reachability

class ReachabilityManager: NSObject {

    static let shared = ReachabilityManager()
    var reachabilityStatus: Reachability.Connection = .none
    let reachability = Reachability()

    var isNetworkAvailable: Bool {
        return reachabilityStatus != .none
    }

    @objc func reachabilityChanged(notification: Notification) {
        guard let reachability = notification.object as? Reachability
            else {
                return
        }
        reachabilityStatus = reachability.connection
        switch reachability.connection {
        case .none:
            NoInternetView.show()
            NotificationCenter.default.post(name: .reachable, object: nil, userInfo: ["connected": false])
        case .wifi, .cellular:
            NoInternetView.hide()
            NotificationCenter.default.post(name: .reachable, object: nil, userInfo: ["connected": true])
        }
    }

    func startMonitoring() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged), name: Notification.Name.reachabilityChanged, object: reachability)
        do {
            try reachability?.startNotifier()
        } catch {
            debugPrint("Could not start reachability notifier")
        }
    }

    func stopMonitoring() {
        reachability?.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: Notification.Name.reachabilityChanged, object: reachability)
    }

}

in AppDelegate call ReachabilityManager.shared.startMonitoring()

steveSarsawa
  • 1,559
  • 2
  • 14
  • 31
Alexandr Kolesnik
  • 1,929
  • 1
  • 17
  • 30
0

I check the answers many of them done with libraries, it is not so hard without library, my answer is for anyone who want to check their status without using library.

First define this function:

let monitor = NWPathMonitor()

  func checkConnetionStatus() -> Bool {
        var status  = Bool()
        monitor.pathUpdateHandler = { pathUpdateHandler in
            if pathUpdateHandler.status == .satisfied {
                print("Internet connection is on.")
                status = true
            } else {
                let alert = UIAlertController(title: "Connection problem", message: "check your connection please", preferredStyle: UIAlertController.Style.alert)
                alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
                alert.popoverPresentationController?.sourceView = self.appDelegate.window.self
                alert.popoverPresentationController?.sourceRect = CGRect(x: (self.appDelegate.window?.center.x)!, y: (self.appDelegate.window?.center.y)!, width: 0, height: 0)
                alert.popoverPresentationController?.permittedArrowDirections = []
                self.appDelegate.window?.rootViewController!.present(alert, animated: true, completion: nil)
                print("There's no internet connection.")
                status = false
            }
        }
        monitor.start(queue: queue)
        return status
    }

Then call it inside where you make request or wherever you want:

  func datarequest() {
          if checkConnetionStatus() == true {
            // do your job here
        }
    }