简体   繁体   English

应用程序进入后台时如何发送本地通知

[英]How to send local notification when application goes to background

i want to send local notification when my application goes to background , the notification comes from calling web service (we couldn't use push notifications because we use local servers and there is no internet access) , i know about background fetch capability and i turned it on in my app but i want another timer to call the webservice every 2 minutes and push notifications if app doesn't terminated , anyone has an idea to do that?我想在我的应用程序进入后台时发送本地通知,该通知来自调用 Web 服务(我们无法使用推送通知,因为我们使用本地服务器并且没有互联网访问),我知道后台获取功能并且我转身它在我的应用程序中打开,但我希望另一个计时器每 2 分钟调用一次网络服务,并在应用程序未终止时推送通知,有人知道这样做吗?

Thanks谢谢

Unfortunately push notifications from your server are the only way to have background tasks on a schedule that you decide.不幸的是,来自您的服务器的推送通知是按您决定的时间表执行后台任务的唯一方法。

Background fetch is for pulling data from a server so it is ready for the user when they open the app, but iOS decides when to use it based on when the user uses the app.后台获取用于从服务器提取数据,以便在用户打开应用程序时为用户准备好,但 iOS 会根据用户使用应用程序的时间来决定何时使用它。

You can detect when the app is backgrounded and schedule a local notification then if necessary, but there is only a short amount of time to execute code before it will be suspended along with any timers you are trying to run.您可以检测应用程序何时进入后台并在必要时安排本地通知,但在代码与您尝试运行的任何计时器一起暂停之前,只有很短的时间来执行代码。

You can detect when the app is going to the background in two ways:您可以通过两种方式检测应用何时进入后台:

  1. Implement the applicationWillResignActive() or UIApplicationDidEnterBackground() methods in your app delegate.在您的应用程序委托中实现applicationWillResignActive()UIApplicationDidEnterBackground()方法。

  2. Register for the UIApplicationDidEnterBackground notification.注册UIApplicationDidEnterBackground通知。

Here is an example of registering for the notification:以下是注册通知的示例:

let center = NotificationCenter.default
center.addObserver(self, selector: #selector(yourMethod), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)

You can also check the app state at any time like this:您还可以随时检查应用程序状态,如下所示:

let state = UIApplication.shared.applicationState
    if state == .background {
        // App is in background
    }
    else if state == .active {
        // App is in foreground
    }

More information on extending background execution time , background app refresh and background modes .有关延长后台执行时间后台应用程序刷新后台模式的更多信息。

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

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