How to call a function every time user opens application

You need to implement your logic in AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

        // first launch
        // this method is called only on first launch when app was closed / killed
        return true
    }

    func applicationWillEnterForeground(application: UIApplication) {

        // app will enter in foreground
        // this method is called on first launch when app was closed / killed and every time app is reopened or change status from background to foreground (ex. mobile call)
    }

    func applicationDidBecomeActive(application: UIApplication) {

        // app becomes active
        // this method is called on first launch when app was closed / killed and every time app is reopened or change status from background to foreground (ex. mobile call)
    }
}

Update

As Paulw11 suggests, consider using applicationWillEnterForeground instead of applicationDidBecomeActive


In ViewController.swift in viewDidLoad() write either of these in respective manner:

NotificationCenter.default.addObserver(self, selector: #selector(self.update), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.update), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)

(EDIT: update for Swift 3)

(EDIT: removed part of this post that was incorrect. iOS triggers these notifications automatically to any added observer, no need to add code to trigger them in the App Delegate)


For Swift 5 use this code

  1. Add this line in func viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.updateView), name: UIApplication.didBecomeActiveNotification, object: nil)

  2. Add This function

    @objc func updateView() {

    }


In your AppDelegate.swift, there are didFinishLaunchingWithOptions and applicationWillEnterForeground.

applicationWillEnterForeground is similar to viewWillAppear for your viewControllers as opposed to your app, while didFinishLaunchingWithOptions is similar to viewDidLoad for your app. For more information, check UIApplicationDelegate

Tags:

Ios

Swift