我正在制作一个计时器,它将使用swift 2,Xcode 7重复调用该函数。该函数发送本地推送通知。我的计时器变量在ViewController.swift的viewDidLoad()外部声明。
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self , selector: Selector("notification"), userInfo: nil, repeats: true)
我收到一个错误:
参数类型'NSObject->()-> ViewController不符合预期的类型'AnyObject'
目标自我似乎有一些问题,因为它以红色突出显示。
如果需要,这是我的完整代码:
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()
}
}
}
提前致谢:)
尝试将var timer仅声明为NSTimer.init()设置为:
var timer = NSTimer.init()
然后,将带有scheduleTimerWithInterval的初始化放入viewDidLoad()中:
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "notification", userInfo: nil, repeats: true)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句