-1

I have code I want it run in click button home or go to background device.

self.ref.child("khlea").child("Users").child(self.user_random!).setValue(nil)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nwrs Nwrs
  • 15
  • 5

1 Answers1

3

You can do this in two ways far as i know.

1 Through Appdelegate Or SceneDelegate (for iOS13)

Write your code in applicationWillResignActive() method in appdelegate and sceneWillResignActive method in scenedelgate.

2 Through Notification Center

NotificationCenter to observe the UIApplicationWillResignActive event. This event is fired every time the application will enter the background.

func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(saveToFirebase), name: UIApplication.willResignActiveNotification, object: nil)
}

func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}
@objc func saveToFirebase(){
    self.ref.child("khlea").child("Users").child(self.user_random!).setValue(nil)
}

In Swift 4.1 + Closure Version

var resignObserver: NSObjectProtocol!
    override func viewDidLoad() {
        super.viewDidLoad()
        resignObserver = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { _ in
            self.ref.child("khlea").child("Users").child(self.user_random!).setValue(nil)
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(resignObserver!)
    }
Community
  • 1
  • 1
Gurtej Singh
  • 225
  • 1
  • 9
  • 1
    You should be using `didEnterBackgroundNotification`, not `willResignActiveNotification` to detect entering the background. – rmaddy Sep 21 '19 at 21:26
  • And the question is closed as a duplicate, no need for this answer. Besides, this no longer works with iOS 13. – rmaddy Sep 21 '19 at 21:26
  • Both can serve the purpose. – Gurtej Singh Sep 21 '19 at 21:32
  • Maybe. It depends on the needs of the app. They are not the same and they are not called at the same time. But again, your answer isn't obsolete with iOS 13 for any app using scenes. – rmaddy Sep 21 '19 at 21:34
  • Yes, i know they don't call at the same time. i never said they are same. – Gurtej Singh Sep 21 '19 at 21:40
  • But your previous comment said they serve the same purpose. Now you say you never said they are the same. I'm confused. Please clarify. – rmaddy Sep 21 '19 at 21:44