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

时间:2018-10-22 14:05:16

标签: swift xcode timer apple-push-notifications appdelegate

我需要让我的应用程序获取数据并根据响应向用户显示警报,我试图创建一个函数,然后在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}
        })


    }

}

我创建了此函数来测试在设置计时器后是否会显示通知,但是发生的是在设置计时器时。如果删除计时器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,电报,tinder之类的应用程序如何在后台状态下处理/获取数据,然后向用户显示通知?

预先感谢您的回答。

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

1 个答案:

答案 0 :(得分:0)

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