简体   繁体   中英

Error in NSTimer (Swift: Xcode)

I am making a timer that will call a function repeatedly with swift 2, Xcode 7. This function sends a local push notification. My timer variable is declared outside the viewDidLoad() in ViewController.swift.

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self ,       selector: Selector("notification"), userInfo: nil, repeats: true)

I am getting an error:

Argument Type 'NSObject -> () -> ViewController does not conform to expected type 'AnyObject'

It seems there is some problem with the target self as it is highlighted in red.

Here is my full code if needed:

import UIKit

class ViewController: UIViewController {

var time = 10
 var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self , selector: Selector("notification"), userInfo: nil, repeats: true)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func btnPressed(sender: AnyObject) {
 let alertView = UIAlertController(title: "You won!", message: "Press Go to continue!", preferredStyle: UIAlertControllerStyle.Alert)
    self.presentViewController(alertView, animated: true, completion: nil)

    alertView.addAction(UIAlertAction(title: "Go", style: UIAlertActionStyle.Default, handler: nil))

}

func notification(){
    time--
    if (time == 0){


    let notification = UILocalNotification()
    notification.alertAction = "Go back to App!"
    notification.alertBody = "Pls Go back to my App!"
    notification.fireDate = NSDate(timeIntervalSinceNow: 0)

    UIApplication.sharedApplication().scheduleLocalNotification(notification)
        timer.invalidate()

}
}

}

Thanks in advance:)

Try to declare the var timer only setting as NSTimer.init() like:

var timer = NSTimer.init()

And then, put the initialization with scheduledTimerWithInterval inside viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "notification", userInfo: nil, repeats: true)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM