本地推送通知在 iOS 中不起作用

问题描述 投票:0回答:1
//
//  LocalNotifications.swift
//  PushNotifications_Tutorial
//
//  Created by Abhishek Gautam on 15/12/23.
//

import SwiftUI
import UserNotifications

class NotificationManager {
    
    static let instance = NotificationManager() // Singleton
    
    func requestAuthorization() {
        
        let options : UNAuthorizationOptions = [.alert, .sound, .badge]
        
        UNUserNotificationCenter.current().requestAuthorization(options: options) { (success, error) in
            if let error = error{
                print("ERROR : \(error)")
            }
            else {
                print("Success!")
            }
        }
    }
    
    func scheduleNotification() {
        
        let content = UNMutableNotificationContent()
        content.title = "This is my first push notification"
        content.subtitle = "This was sooooo much fun!"
        content.sound = .default
        content.badge = 1
        
        //time
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.0, repeats: false)
        //calender
        //location
        
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request)
    }
}

struct LocalNotifications: View {
    var body: some View {
        VStack(spacing :40){
            Button("Request Permission") {
                NotificationManager.instance.requestAuthorization()
                //print("Button Tapped!")
            }
            Button("Schedule Notification") {
                NotificationManager.instance.scheduleNotification()
            }
        }
    }
}

#Preview {
    LocalNotifications()
}

一切似乎都工作正常,但问题是通知没有显示。我正在尝试从 YouTube 视频中学习 iOS 中的推送通知,事情似乎对 YouTube 用户来说效果很好,但我也做了同样的事情,但它不适合我。

我尝试获取用户的权限,成功了。但是当涉及到通知的弹出部分时,它没有显示。请帮忙。

ios swift swiftui push-notification
1个回答
0
投票

当应用处于后台状态并收到通知时,系统直接向用户显示通知。但在前台状态下,系统会将通知传递给我们的应用程序,而不是显示给用户。

要在前台状态显示通知或处理通知的用户交互,我们必须实现 UNUserNotificationCenterDelegate,并且必须在应用程序从 application(_:, didFinishLaunchingWithOptions:) 返回之前设置委托。

详情请查看Apple文档:https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app

我通过添加以下代码解决了该问题。

使用AppDelegate实现UNUserNotificationCenterDelegate:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // Set notification center delegate, otherwise delegate methods won't work
        UNUserNotificationCenter.current().delegate = self
        return true
    }
}

extension AppDelegate : UNUserNotificationCenterDelegate {
    // To receive notification in foreground state, you have to implement the completion hanlder properly, otherwise the notification will not be presented.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        print("willPresent:")

        completionHandler([.banner, .list, .badge, .sound])
    }

    // Handle user interactions to the notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        print("didReceive:")

        completionHandler()
    }
}

在 SwiftUI 应用程序中添加 AppDelegate:

@main
struct NotificationApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
© www.soinside.com 2019 - 2024. All rights reserved.