Addev
Addev

Reputation: 32253

Detect when a view controller goes to background and gets resumed

I'm implementing a ViewController with the following requirement: If the user returns to the app after 15 minutes, the view should reload the data.

I was thinking on using viewDidDisappear to save the timestamp when the app went to background and viewDidAppear for checking previously saved values and refresh if needed, but this methods are not getting called when switching between apps.

How can I solve this in a easy way?

Upvotes: 17

Views: 14389

Answers (5)

Dario Pellegrini
Dario Pellegrini

Reputation: 1768

If interested here is a RxSwift version

NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).subscribe(onNext: { [weak self] _ in
            
}).disposed(by: disposeBag)

NotificationCenter.default.rx.notification(UIApplication.willResignActiveNotification).subscribe(onNext: { [weak self] _ in

}).disposed(by: disposeBag)

Upvotes: 1

Rohejul Islam
Rohejul Islam

Reputation: 126

Objective-C

- (void)viewDidLoad {
     [[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(appMovedToBackground:)
       name:UIApplicationDidEnterBackgroundNotification
     object:nil];

     [[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(appBecomeActive:)
       name:UIApplicationDidBecomeActiveNotification
     object:nil];
}

- (void)appMovedToBackground:(NSNotification *) notification  {
    NSLog(@"App Moved To Background");
}

- (void)appBecomeActive:(NSNotification *) notification {
    NSLog(@"App become active");
}

Don't forget to clear notifications when view gets disappear

Upvotes: 1

Anbu.Karthik
Anbu.Karthik

Reputation: 82756

use UIApplicationDidBecomeActive for resume and UIApplicationWillResignActive for handle goes background

SwiftUI

Text("check application state!")
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
                    print("User received on  willResignActiveNotification!")
                }
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
                    print("User received on  didBecomeActiveNotification!")
                }

Swift 5.x > above

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name:  UIApplication.didBecomeActiveNotification, object: nil)
    }

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.openAndCloseActivity), name: UIApplication.willResignActiveNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.openAndCloseActivity), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc func openAndCloseActivity(_ notification: Notification)  {
    if notification.name == UIApplication.didBecomeActiveNotification{
        // become active notifictaion
    }else{
        // willResignActiveNotification
    }
    
}

Swift 5.x < below

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()
    
    NotificationCenter.default.addObserver(self, selector: #selector(self.closeActivityController), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.openactivity), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
   
    
}

and handle the method as

func closeActivityController()  {
    
    
}

func openactivity()  {
    
    //view should reload the data.
}

other notification types are

extension NSNotification.Name { 
@available(iOS 4.0, *)
public static let UIApplicationDidEnterBackground: NSNotification.Name

@available(iOS 4.0, *)
public static let UIApplicationWillEnterForeground: NSNotification.Name

public static let UIApplicationDidFinishLaunching: NSNotification.Name

public static let UIApplicationDidBecomeActive: NSNotification.Name

public static let UIApplicationWillResignActive: NSNotification.Name

public static let UIApplicationDidReceiveMemoryWarning: NSNotification.Name

public static let UIApplicationWillTerminate: NSNotification.Name

}

Upvotes: 33

Emin Turk
Emin Turk

Reputation: 456

Swift 5

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)

Methods :

@objc func appMovedToBackground() {
       print("App moved to background!")
    }
@objc func appBecomeActive() {
       print("App become active")
    }

To remove observers

override func viewWillDisappear(_ animated: Bool) {
      let notificationCenter = NotificationCenter.default
        notificationCenter.removeObserver(self, name:UIApplication.willResignActiveNotification, object: nil)
        notificationCenter.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
    }

Upvotes: 19

Tom E
Tom E

Reputation: 1607

UIApplicationDelegate has these two functions:

applicationDidEnterBackground(_:)
applicationDidBecomeActive(_:)

These could well be what you need.

Upvotes: 0

Related Questions