Swift 如何使用 NSTimer 后台? [英] Swift how to use NSTimer background?

查看:22
本文介绍了Swift 如何使用 NSTimer 后台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class ViewController: UIViewController {

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

    func update() {
       println("Something cool")
    }
}

模拟器没问题,我会通过点击home键得到连续的Something cool".但是当我用我的 iPhone 调试应用程序时,它就成功了.当我点击主页按钮并使我的应用程序在后台运行时,我什么也没得到.有人告诉我我可以播放一段很长的空白音乐来让我的应用程序在后台运行.但是我不知道如何用 swift @matt 在后台播放音乐

It's ok for the Simulator ,I will get continuous "Something cool" through I tapped the home button. But it worked out when I debug the app with my iPhone. I did't get anything when I tapped the home button and make my app run background. Someone told me I can play a long blank music to make my App run in the background.But I don't know how to play music in the background with swift @matt

推荐答案

你可以使用 beginBackgroundTaskWithExpirationHandler 来获取一些后台执行时间.

You can use beginBackgroundTaskWithExpirationHandler to get some background execution time.

class ViewController: UIViewController {
    var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

    override func viewDidLoad() {
        super.viewDidLoad()
        backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
        })
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
    }

    func update() {
        println("Something cool")
    }
}

Swift 3.0

backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
    UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})

此代码的灵感来自 this answer,但我移植到了 swift.

This code was inspired by this answer, but I ported to swift.

这显然只在 iOS 7+ 上运行 3 分钟.

This apparently only runs for 3 minutes on iOS 7+.

这篇关于Swift 如何使用 NSTimer 后台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆