有没有办法在iOS Swift 5上应用程序处于前台时获取推送通知?



我想为iOS创建考勤管理应用程序。 该应用程序将具有开始按钮,然后如果点击该应用程序将具有横幅通知以迎接您。

问题是当应用程序处于前台时,我无法获得横幅通知。我将在下面显示我的代码。如果我想收到通知,我必须返回主屏幕或运行其他应用程序。 在我的应用程序上,Set Notification按钮可以接收通知,Start按钮用于设置通知。我会立即收到通知,但此时我必须回家,所以我将时间定timeInterval: 5

内容视图.swift

import SwiftUI
import Foundation
import UserNotifications
struct ContentView: View {
var body: some View {
VStack {
Button(action: { self.setNotification() }) {
Text("Set Notification")
}.padding()
//added here
Button(action: { self.btnSend() }) {
Text("Start")
}.padding()
}
}
func setNotification() -> Void {
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound,.badge], completionHandler: {didAllow,Error in
print(didAllow) //
})
}
func btnSend() {
print("btnSend")
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Good morning hehe", arguments: nil)
content.sound = UNNotificationSound.default
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "FiveSecond",
content: content, trigger: trigger) // Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
// Handle any errors
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

有人有好的解决方案吗?

可能您只需要在AppDelegate中添加一些代码即可。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// add UNUserNotificationCenterDelegate
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
-> Void) {
completionHandler([.alert, .badge, .sound])
} // add this function
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self // add this
return true
}
// ... omitted
}

使用

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent   notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)   { 
completionHandler([.alert, .sound])
}

用于前台通知捕获和显示警报、徽章和添加声音的方法。

如果应用程序位于前台,则通知横幅不显示,您需要捕获AppDelegate中的通知,创建自己的自定义视图并从那里处理它。

最新更新