在Swift中,当应用程序运行后,如何在AppDelegate中验证NSTimer?

时间:2014-10-25 15:17:35

标签: ios swift xcode6 nstimer appdelegate

我需要将我的iOS应用程序从obj-c转换为swift。我在NStimer中有ViewController,每隔30秒从shoutcast加载元数据,但当应用程序重新启动时,它会停止,当进入前台时,它会再次运行。

编辑:好的。问题解决了!我在viewDidLoad中添加了两个名为UIApplicationWillResignActiveNotificationUIApplicationWillEnterForegroundNotification的观察者,如下所示:

override func viewDidLoad() {
    NSLog("System Version is \(UIDevice.currentDevice().systemVersion)");
    super.viewDidLoad()
    self.runTimer()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "invalidateTimer", name: UIApplicationWillResignActiveNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "runTimer", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

我做了两个功能。第一个用于运行计时器:

func runTimer(){
    loadMetadata()
    myTimer.invalidate()
    NSLog("timer run");
    myTimer = NSTimer.scheduledTimerWithTimeInterval(30.0, target: self, selector: "loadMetadata", userInfo: nil, repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()
    mainLoop.addTimer(myTimer, forMode: NSDefaultRunLoopMode)
}

第二个阻止它:

func invalidateTimer(){
    myTimer.invalidate()
    NSLog("timer invalidated %u", myTimer);
}

我希望这可以帮助别人。 :)

1 个答案:

答案 0 :(得分:0)

我建议你为你的任务使用适当的系统:https://developer.apple.com/library/ios/documentation/iphone/conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW56

  

需要定期检查新内容的应用可以询问   系统唤醒它们,以便它们可以启动一个获取操作   那个内容。要支持此模式,请启用后台提取选项   来自您的“功能”选项卡的“背景模式”部分   Xcode项目。 (您也可以通过添加支持来启用此支持   UIBackgroundModes键与应用程序的Info.plist中的获取值   文件。)...

     

当出现好机会时,系统会唤醒或启动您的应用   进入后台并调用app delegate   application:performFetchWithCompletionHandler:方法。使用该方法   检查新内容并在内容时启动下载操作   是可用的。