Joe Joe - 4 months ago 35
iOS Question

Swift - How to call a function every time user opens application

I want to call the function named update every time user taps my app's icon and open it. How would I do that? Which method fires that I can override whenever the app launches no matter is killed from background or user pressed the home button.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var label: UILabel!

@IBOutlet weak var button: UIButton!

@IBOutlet weak var labeltwo: UILabel!

var NSDateDefalt = NSUserDefaults.standardUserDefaults()
var date : NSDate?

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
date = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as? NSDate
label.text = "\(date)"
update()
}


@IBAction func buttona(sender: AnyObject) {
date = NSDate()
label.text = "\(date)"

NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey:"yourKey")
}



func update(){
let now = NSDate()
let seconds = now.timeIntervalSinceDate(date!)
labeltwo.text = "\(seconds))"
}

}

Answer

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