I am working on iOS application. I have to call api while user online and offline.
I have viewcontroller 1 class and there I am calling api.
override func viewDidLoad() {
super.viewDidLoad()
if let reachability = manager.sharedInstance.internetReachability {
NotificationCenter.default.addObserver( self, selector: #selector( self.reachabilityChanged),name: Notification.Name.reachabilityChanged, object: reachability )
}
}
@IBAction func callAPI(_ sender: Any) {
self.callApi()
}
func callApi() {
//call api
}
@objc private func reachabilityChanged( notification: NSNotification ) {
let reachability = notification.object as! Reachability
switch reachability.connection {
case .wifi:
self.callApi()
case .cellular:
self.callApi()
case .none:
case .unavailable:
}
}
The issue is here if I am in viewcontroller 2 class and app comes to online, The api is not getting trigger in Viewcontroller 1. The requirement is, If user is offline and comes to online, user is in viewcontroller 2, I have to call that api in viewcontroller 1 without any action, Just by tracking internet is active and I have to call API.
Any suggestions?
The problem is if there is no instance of the view controller 1 existed at the time of connectivity changes, you have no chance to call the API.
If you have no reason having to keep the calling API inside the view controller 1 when connectivity changes, I suggest moving the observer to somewhere that can alive throughout your app's lifetime. The simplest place is in AppDelegate.