For some unspecified time you can attain this by using Background Fetch.
override init() {
super.init()
initializeBackgroundTask()
NotificationCenter.default.addObserver(self, selector: #selector(networkHasChanged(notification:)), name: NSNotification.Name.reachabilityChanged, object: nil)
}
func networkHasChanged(notification : NSNotification) {
if let reachability = notification.object as? Reachability {
// Do whatever you want to do!!!
}
}
func initializeBackgroundTask() {
if bgTask == UIBackgroundTaskInvalid {
bgTask = UIApplication.shared.beginBackgroundTask(withName: "CheckNetworkStatus", expirationHandler: {
self.endBackgroundTask()
})
}
}
func endBackgroundTask() {
if deepLinkString == nil {
if (self.bgTask != UIBackgroundTaskInvalid) {
UIApplication.shared.endBackgroundTask(self.bgTask)
self.bgTask = UIBackgroundTaskInvalid
}
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.reachabilityChanged, object: nil)
}
Also try not to initialise background task if not in use.