[iOS] Swift how to use NSTimer background?

使用 Timer 範例:

    var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

    override func viewDidLoad() {

        super.viewDidLoad()

        backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {

            UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)

        })

        _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.scheduleNotification), userInfo: nil, repeats: true)

    }

    

    @objc func scheduleNotificati

Just store the instance of your timer and then when you are moving to another Controller invalidate the timer, so that first declare one instance of NSTimer.

var timer:Timer?

Now use this object to store the reference of your scheduledTimer.

self.timer = Timer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(DriversInterfaceViewController.CheckFormularChild), userInfo: nil, repeats: true)

Now on moving to another controller simply.

self.timer.invalidate()
on() {         print("timer hello")     }

停掉 Timer:

 

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *