繁体   English   中英

NSTimer的单例未从AppDelegate触发

[英]Singleton with NSTimer not firing from 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触发一次,然后不再触发。

关于我所缺少的任何线索都是很好的。

更改您的下载功能;

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")
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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