首页 > 解决方案 > 在 Swift 上实现后台功能

问题描述

我最近刚刚完成了一个应用程序,它基本上有一个 Firebase 数据库的观察者,当某个属性发生变化时,会发送一个横幅类型通知。该应用程序完全可以运行,但是当我在使用手机时将应用程序置于后台时,我意识到它没有运行任何代码或发送通知。

如何实现让观察者在后台监听数据库的任何更改,以及发送通知?

这是通知授权请求功能:

func requestNotificationAuthorization() {
    let authOptions = UNAuthorizationOptions.init(arrayLiteral: .alert, .badge, .sound)
    
    self.userNotificationCenter.requestAuthorization(options: authOptions) { (success, error) in
        if let error = error {
            print("Error: ", error)
        }}}

通知中心功能:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    completionHandler()
}

发送通知功能:

func sendNotification() {
    // Create new notifcation content instance
    let notificationContent = UNMutableNotificationContent()

    // Add the content to the notification content
    notificationContent.title = "P2P Tracker"
    notificationContent.body = (PriceTimeDate ?? "")
    print(notificationContent.body)
    notificationContent.badge = NSNumber(value: 1)

    // Add an attachment to the notification content
    if let url = Bundle.main.url(forResource: "dune",
                                    withExtension: "png") {
        if let attachment = try? UNNotificationAttachment(identifier: "dune",
                                                            url: url,
                                                            options: nil) {
            notificationContent.attachments = [attachment]
        }
    }
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3,
                                                    repeats: false)
    let request = UNNotificationRequest(identifier: "testNotification",
                                        content: notificationContent,
                                        trigger: trigger)
    userNotificationCenter.add(request) { (error) in
        if let error = error {
            print("Notification Error: ", error)
        }
    }
}

标签: iosswiftfirebasebackground

解决方案


推荐阅读