计时器无法正常工作 iPhone

Timer not working on real iPhone

我正在尝试使用本地通知,但有些东西不起作用。

我有一个 class 通知来处理与通知相关的所有代码。 它显然有效。不起作用的是我尝试触发通知的方式。

当用户单击主页按钮时,我会调用启动 NSTimer 的通知 class。它每秒重复一次,我每 10 秒调用一次网络服务。

一切都在我的模拟器上运行良好,但在我的真实设备上却无法运行 iPhone。

这里是代码:

//as a class variable
let notif = Notification()

func applicationDidEnterBackground(application: UIApplication) {

        notif.triggerTimer()

    }

通知class

class Notification: NSObject, WsOrderStatusProtocol, WsPinRequestProtocol {

    var timer = NSTimer()
    var time = 0
    var sendNotification:Bool = true

    var wsos = WsOrderStatus()
    var wsoc = PinRequest()

    override init() {
        super.init()
        self.wsos.delegate = self
        self.wsoc.delegate = self
    }

    func triggerTimer() {
        print("log INFO : class Notification, methode : triggerTimer")

        NSNotificationCenter.defaultCenter().addObserver(self, selector:"orderCoupon:", name: "actionOrderCouponPressed", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"cancelTimer:", name: "actionCancelTimerPressed", object: nil)

        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("launchNotification"), userInfo: nil, repeats: true)

    }

    func launchNotification() {
        print("log INFO : class Notification, methode : launchNotification")

        time += 1

        print("time \(time)")

        if time % 10 == 0 {
            print("modulo 10")
            wsos.getOrderStatus()
        }


    }    

}

在模拟器中,我看到日志和计数为 10 的日志等,但是对于我的真实 iphone,我只看到第一个日志 "print("log INFO:class 通知,方法:triggerTimer")" 然后什么都没有...

你知道为什么吗?

正如 Paul 在他的评论中所说,您的应用程序在暂停之前只会在后台停留很短的时间。暂停意味着您的代码不再 运行,因此计时器停止。

模拟器并不总是遵循相同的规则。当它的行为与设备的行为不同时,请忽略它。它在说谎。

如果您想有更多的时间在后台工作,可以使用beginBackgroundTaskWithExpirationHandler的方式申请。在您的 applicationDidEnterBackground 方法中进行调用。

根据测试,我发现这会给你 3 分钟的额外时间。之后你的到期处理程序块被执行,然后你被暂停。

Apple 不希望您的应用 运行无限期地从后台运行。它会耗尽电池电量。

我发现可以撒谎并告诉系统您是一个从后台播放声音的应用程序,然后编写您的过期处理程序来播放一段短片 "sound of silence" 然后请求另一个使用 beginBackgroundTaskWithExpirationHandler 的后台任务。但是,这样做会使您被应用商店拒绝。