单个NSTimer没有从AppDelegate触发

时间:2015-08-30 05:54:55

标签: ios swift singleton nstimer appdelegate

我正在尝试从我的NSTimer中获取一个AppDelegate的单身人士,以便在应用程序运行期间触发。虽然我可以在Objective-C中使它工作,但我似乎无法确定它为什么不能在Swift中工作。每隔30秒,我希望它轮询服务器并下载正在等待的任何消息。

我在 AppDelegate 中的代码是:

var myGetMessages:GetMessages!

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    ..lots of other things ..

    myGetMessages = GetMessages.sharedInstance
    myGetMessages.downloadMessages()
}

我的 Singleton 有:

class GetMessages {

static let sharedInstance = GetMessages()

var messageDownloadTimer: NSTimer?

.. other init code ....

func downloadMessages() {
    if myMainUser != nil {
        if messageDownloadTimer == nil {
            self.getMessagesFromServer(false, completionHandler: nil)
            messageDownloadTimer = NSTimer(timeInterval: 30, target: self, selector: "downloadNewMessages", userInfo: nil, repeats: true)
        }
    } else {
        println("There is no MainUser set up, so can't download Messages")
    }

}

它从AppDelegate触发一次,然后再也不会。

任何关于我缺少什么的线索都会很棒。

1 个答案:

答案 0 :(得分:1)

更改下载功能;

func downloadMessages() {
    if messageDownloadTimer == nil {
         //?? messageDownloadTimer = NSTimer(timeInterval: 30, target: self, selector: "downloadNewMessages", userInfo: nil, repeats: true)
         messageDownloadTimer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: "downloadNewMessages", userInfo: nil, repeats: true)
    }
    //--
    if myMainUser != nil {
       self.getMessagesFromServer(false, completionHandler: nil)
    } else {
        println("There is no MainUser set up, so can't download Messages")
    }
}