2015-10-15 24 views
0

我正在製作一個計時器,它將用swift 2,Xcode 7重複調用一個函數。此函數發送本地推送通知。我的計時器變量是在ViewController.swift中的viewDidLoad()之外聲明的。NSTimer中的錯誤(Swift:Xcode)

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

我得到一個錯誤:

參數類型「NSObject的 - >() - >視圖控制器不符合預期的類型 '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() 

} 
} 

} 

感謝提前:)

回答

3

試圖聲明瞭var定時器設置僅作爲NSTimer.init(如:

var timer = NSTimer.init() 

然後,將scheduledTimerWithInterval的初始化放在viewDidLoad()中:

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

非常感謝:D工作! –