ios - 在 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)
}
}
}
解决方案
推荐阅读
- python - 在一组值上优化函数
- python - Python - 如何使用 .format 附加到列表
- spring-boot - Spring Boot 验证数据源连接
- python - 使用 f 字符串格式化字符串
- python - PyCharm 使用 TensorFlow 2 报告导入错误
- mysql - MySQL 8 InnoDB 分区 - 最大分区数
- java - 我应该安装哪个 Java JDK 才能使用 Android Studio
- encoding - url 编码问题 - tableau js api
- php - 如何将 div 添加到最后一个帖子和每 5 个帖子
- r - 仅当满足条件时才在 dplyr 组中过滤,否则不过滤