There are two ways to check network connectivity, either you can set an observer for network connection changes so that you will get notified whenever the network connection status changes(either connected or disconnected).
(You can check network connectivity using iOS Reachability class or you can use AFNetworking library for same)
If you want to continuously monitor network changes you should set observer as follows:
Add this code to your didFinishLaunchingWithOptions in AppDelegate
NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkNetworkStatus", name: ReachabilityChangedNotification, object: nil);
do{self.reachability = try Reachability.reachabilityForInternetConnection()}catch{}
do{try self.reachability.startNotifier()}catch{
}
self.performSelector("checkNetworkStatus", withObject: nil, afterDelay: 0.6)
Add below code to your AppDelegate
var networkStatus : Reachability.NetworkStatus!
var objNetworkStatusView : NetworkStatusView! = nil
func checkNetworkStatus()
{
networkStatus = reachability.currentReachabilityStatus
if (networkStatus == Reachability.NetworkStatus.NotReachable)
{
print("Not Reachable")
objNetworkStatusView = NetworkStatusView(frame:CGRectMake(0, 0, self.window!.frame.size.width, self.window!.frame.size.height))
UIApplication.sharedApplication().keyWindow?.addSubview(objNetworkStatusView)
UIApplication.sharedApplication().keyWindow?.bringSubviewToFront(objNetworkStatusView)
}
else
{
print("Reachable")
if((objNetworkStatusView) != nil)
{
objNetworkStatusView.removeFromSuperview()
}
}
}
And if you just want to check network connectivity before making request to your service you should check network connection manually as follows:
Create instance of delegate in the class where you have to call web service or you have to check network connectivity,
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
And check network connectivity as
if (delegate.networkStatus==Reachability.NetworkStatus.NotReachable) {
delegate.checkNetworkStatus()
} else {
//You can call web service here
}