当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - 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)
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: