swift - 如何在 appDelegate 方法上设置计时器计划?

标签 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}
        })


    }

}

我创建这个函数是为了测试在设置计时器后通知是否会显示,但是当我设置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、Telegram、Tinder 等应用程序如何处理/获取后台状态数据,然后向用户显示通知?

提前感谢您的回答。

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

最佳答案

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

关于swift - 如何在 appDelegate 方法上设置计时器计划?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52931306/

相关文章:

ios - 来自 Performance Wise : Class Computed Property vs Stored Property

SwiftUI - 将数据传递到不同的 View

ios - 线程 1 : EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP) Error

ios - ASIHTTPREQUEST xCode - 设置委托(delegate)时崩溃

ios - WatchKit 定时器结束时的函数

javascript - 点击后退按钮后停止 Angular $timeout 计时器

swift - 将 Cookie 设置为来自 Swift NSURLSession 的 HTTP POST 请求

swift - Alamofire 返回错误

java - 如何在不阻塞计时器(Java Swing)的情况下暂停程序执行?

swift - 如何将 View Controller 推送到生成的导航层次结构中