如何在 appDelegate 方法上设置 Timer 时间表?

Posted

技术标签:

【中文标题】如何在 appDelegate 方法上设置 Timer 时间表?【英文标题】:How to set a Timer schedule on appDelegate method? 【发布时间】:2018-10-22 14:05:16 【问题描述】:

我需要让我的应用获取数据并根据响应向用户显示警报,我正在尝试创建一个函数,然后在 appDelegate 类上调用它...

功能:

func triggerPushMessages()

    Timer.scheduledTimer(withTimeInterval: 60, repeats: true)  (time) in

    // I want to perform a request here to show the alert to user




    let content = UNMutableNotificationContent()
    content.title = "testNotifications on background state"
    content.body = "date of notification: \(Date().timeIntervalSinceNow)"

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    let notificationRequest = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(notificationRequest, withCompletionHandler:  (err) in
            if let error = err print(error);return
        )


    


我创建了这个函数来测试我设置定时器后通知是否会显示,但是当我设置 timer.schedule 函数时,pushNotification 不起作用,如果我删除定时器 pushNotification 工作......

问题是,我需要先从 Api 请求数据,等待响应,然后显示推送通知以提醒用户...

我该怎么做?

我调用这个方法:

 func applicationDidEnterBackground(_ application: UIApplication) 
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        self.triggerPushMessages()


    

有可能吗? whatsapp、电报、火种等应用如何处理/获取后台状态数据,然后向用户显示通知?

提前感谢您的回答。

我想补充一点,我的 60 秒请求仅用于测试目的,我将每小时执行一次请求...

【问题讨论】:

【参考方案1】:

您不能在应用后台状态添加 60 秒计时器。它在 ios 中是不允许的。如果即使应用程序在后台/不在后台也想向用户显示通知,您可以通过集成 APNS(Apple 推送通知)从后端服务器发送推送通知。因为您是说一旦 api 响应到来,您想向用户显示通知。在这种情况下,服务器将拥有数据,它可以决定并向用户发送通知。

【讨论】:

以上是关于如何在 appDelegate 方法上设置 Timer 时间表?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 AppDelegate 中使用 Parse 正确设置 Facebook iOS SDK?

如何从 AppDelegate 调用在 ViewController 中声明的方法

在 AppDelegate.m 上设置 label.text

iOS 如何在 AppDelegate 中以编程方式设置侧边栏菜单?

如何与 AppDelegate 中的特定视图交互?

如何在 AppDelegate 中将视图控制器设置为根视图控制器