如何在iOS后台运行服务以接收本地通知? [英] How to run a service in iOS background to receive local notification?

查看:299
本文介绍了如何在iOS后台运行服务以接收本地通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与服务器建立MQTT连接的应用程序上工作,并且服务器正在发送与设备和UI更改相关的一些值.但是,当应用程序在后台运行时,用户应获取有关某些值已更改的本地通知.我知道iOS不允许后台服务,但我想确保没有办法实现这一目标.

I am working on app where there is an MQTT connection with the server and server is sending some values related to device and UI changes accordingly. But when app is in background user should get local notification that certain values are changed. I know background service are not allowed in iOS but I want to make sure that is that there is no way to achieve this.

我通过UIApplication.shared.beginBackgroundTask在后台成功添加了带有应用程序的本地通知,但是该通知仅在苹果终止该应用程序后3分钟内有效.

I successfully added local notification with app in background by UIApplication.shared.beginBackgroundTask but it's only work for 3 min exact after that apple terminates the app.

    func registerBackgroundTask() {
        backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.endBackgroundTask()
        }
        assert(backgroundTask != UIBackgroundTaskInvalid)
    }
    func endBackgroundTask() {
        print("Background task ended.")
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskInvalid
    }

仅调用self.registerBackgroundTask()即可使该应用在后台运行三分钟.

And just calling self.registerBackgroundTask() makes the app runnable in background for three min.

接下来我要尝试的是后台获取和窗口小部件来运行服务,在这里我只想提出一些建议,即以上两种方法中的一种可能会起作用吗?

Next that I am going to try is that background fetch and widget to run service, Here I just want some suggestion that is there any chance that one of above two will work ?

推荐答案

听起来像与外部附件通信"将是适合您的应用程序的背景模式. 请参阅 Apple Docs 作为参考. 您必须为项目激活Backround模式,并将其值设置为"external-accessory".然后,您可以在后台进行正在进行的小下载.苹果以心率监测器为例.

It sounds like "Communicating with an External Accessory" would be the background mode that fits your application. See Apple Docs for reference. You have to activate Backround Mode for your project and set the value to "external-accessory". Then you can do ongoing small downloads in background. Apple mentions heart rate monitors as an example.

请注意,连续的背景轮询会浪费能源,并且会很快耗尽电池电量.检查您的应用程序是否真的需要这样做.如果用户仅需要很少的通知/警报,则远程通知将是更好的解决方案.我在自己的项目中使用了远程通知,它的运行非常平稳和可靠.另一个好处是,即使用户之前已经关闭它,它也会唤醒一个应用程序.

Please note that continous background polling is waste of energy and would deplete battery quickly. Check if this is really needed for your application. If the user just needs infrequent notifications/alarms, remote notifictions would be a much better solution. I use remote notifications in my own projects and it works very smooth and reliable. Additional benefit is, that it would wake up an app even if the user has closed it before.

这篇关于如何在iOS后台运行服务以接收本地通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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