2

I was wondering if there is a best way to detect any change happens to Internet Connection

i mean using this code

import SystemConfiguration
var isConnected: Bool = false
func isConnectedToNetwork()
{

var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)

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

var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
    self.isConnected = false
}

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

if isReachable && !needsConnection
{
  self.isConnected = true
} 
else{
     self.isConnected = false
   }  
    }

it returns the status for Internet Connection, but even though i need to keep checking for Internet connection while the app is running so i used this code

NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: Selector("isConnectedToNetwork"), userInfo: nil, repeats: true)

Each 10 seconds it checks for internet connection, but i believe there is a better way. i mean using an observer or something else.

such as this one

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow", name: UIKeyboardDidShowNotification, object: nil)

when the keyboard shows it detects it and calls the function keyboardDidShow()

Mohamed Horani
  • 544
  • 3
  • 9
  • 23
  • SCNetworkReachability has a function to install a callback that is called automatically on changes. However, using this (C based) callback from Swift is possible only with the new Swift 2. See my latest update to http://stackoverflow.com/a/27142665/1187415. – Martin R Jun 14 '15 at 11:04
  • There is this library in github https://github.com/tonymillion/Reachability – mustafa Jun 14 '15 at 11:06
  • @mustafa: That library also uses (if I see it correctly) a *timer* to check for network changes regularly. The reason is that C-style callbacks could not be used in Swift 1.x. – Martin R Jun 14 '15 at 11:08
  • It has notification support too @Martin R – mustafa Jun 14 '15 at 11:10
  • @mustafa: I did not deny that. But it uses a timer internally. – Martin R Jun 14 '15 at 11:11

1 Answers1

3

Swift 3.0+

This is the most clean solution I managed to reach.

You need to install this pod https://github.com/AFNetworking/AFNetworking

Then import AFNetworking where you declare NetworkReachability class.

final class NetworkReachability {
    private var previousStatus: AFNetworkReachabilityStatus = .unknown

    /// Retrieves current network status once and stops monitoring reachability.
    func getCurrentNetworkStatus(completion: ((AFNetworkReachabilityStatus) -> Void)?) {
        previousStatus = .unknown
        startMonitoring { currentStatus in
            completion?(currentStatus)
            self.stopMonitoring()
        }
    }

    /// Monitors network reachability changes until reachable status is present. Then stops monitoring.
    func getReachableNetworkStatus(completion: ((AFNetworkReachabilityStatus) -> Void)?) {
        stopMonitoring()
        startMonitoring { currentStatus in
            completion?(currentStatus)
            if currentStatus == .reachableViaWiFi || currentStatus == .reachableViaWWAN {
                self.stopMonitoring()
            }
        }
    }

    /// Monitors network reachability changes, until stopMonitoring() is called.
    func startMonitoring(newStatusCallback: ((AFNetworkReachabilityStatus) -> Void)?) {
        AFNetworkReachabilityManager.shared().startMonitoring()
        AFNetworkReachabilityManager.shared().setReachabilityStatusChange { currentStatus in
            if currentStatus != .unknown && currentStatus != self.previousStatus {
                newStatusCallback?(currentStatus)
            }
            self.previousStatus = currentStatus
        }
    }

    func stopMonitoring() {
        previousStatus = .unknown
        AFNetworkReachabilityManager.shared().stopMonitoring()
    }
}
klaudas
  • 427
  • 5
  • 13