Swiftui 如何解决';不接受通知。您可以稍后在iOS设置下打开它们';问题

Swiftui 如何解决';不接受通知。您可以稍后在iOS设置下打开它们';问题,swiftui,onesignal,Swiftui,Onesignal,我使用onesignal进行推送通知,它在ios 14升级之前一直运行良好。当我在Xcode 12上构建相同的应用程序而没有任何更改时,我在控制台中收到了这个警告 不接受通知。您可以稍后在iOS下打开它们 背景 在iOS 13上没有问题,这是在我更新到iOS 14时发生的 AppDelegate.swift import UIKit import CoreData import Firebase import GoogleMobileAds import OneSignal import Use

我使用onesignal进行推送通知,它在ios 14升级之前一直运行良好。当我在Xcode 12上构建相同的应用程序而没有任何更改时,我在控制台中收到了这个警告

不接受通知。您可以稍后在iOS下打开它们 背景

在iOS 13上没有问题,这是在我更新到iOS 14时发生的

AppDelegate.swift

import UIKit
import CoreData
import Firebase
import GoogleMobileAds
import OneSignal
import UserNotifications
import SDWebImageWebPCoder

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, OSPermissionObserver, OSSubscriptionObserver {
    
    var window: UIWindow?
    var shortcutItemToProcess: UIApplicationShortcutItem?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        FirebaseApp.configure()
        
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        
        let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false, kOSSettingsKeyInAppLaunchURL: false]
        
        OneSignal.initWithLaunchOptions(launchOptions,
                                        appId: "my key is here",
                                        handleNotificationAction: nil,
                                        settings: onesignalInitSettings)
        OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification
        OneSignal.promptForPushNotifications(userResponse: { accepted in
           print("User accepted notifications: \(accepted)")
         })
        
        // Add your AppDelegate as an obsserver
        OneSignal.add(self as OSPermissionObserver)
        
        OneSignal.add(self as OSSubscriptionObserver)
        
        registerForPushNotifications()
        
        let WebPCoder = SDImageWebPCoder.shared
        SDImageCodersManager.shared.addCoder(WebPCoder)
        
        
        return true
    }
    
    
    func registerForPushNotifications() {
        
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.delegate = self
        
        let readAction = UNNotificationAction(identifier: "oku", title: "Haberi Oku", options: [.foreground])
        let closeAction = UNNotificationAction(identifier: "kapat", title: "Kapat", options: [])
        
        let category = UNNotificationCategory(identifier: "etkilesim", actions: [readAction, closeAction], intentIdentifiers: [], options: [])
        
        notificationCenter.setNotificationCategories([category])
    }
    
    func onOSPermissionChanged(_ stateChanges: OSPermissionStateChanges!) {
        if stateChanges.from.status == OSNotificationPermission.notDetermined {
            if stateChanges.to.status == OSNotificationPermission.authorized {
                print("Thanks for accepting notifications!")
            } else if stateChanges.to.status == OSNotificationPermission.denied {
                print("Notifications not accepted. You can turn them on later under your iOS settings.")
            }
        }
    }
    
    func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
        if !stateChanges.from.subscribed && stateChanges.to.subscribed {
            print("Subscribed for OneSignal push notifications!")
        }
    }
    
    // MARK: UISceneSession Lifecycle
    
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        
        // Grab a reference to the shortcutItem to use in the scene
        if let shortcutItem = options.shortcutItem {
            shortcutItemToProcess = shortcutItem
        }
        
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
    
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        completionHandler([.alert, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        var postId:String = ""
        var postType:String = ""
        
        if let custom = response.notification.request.content.userInfo["custom"] as? NSDictionary{
            if let a = custom["a"] as? NSDictionary{
                if let id = a["id"] as? String{
                    postId = id
                }
                if let type = a["rights"] as? String{
                    postType = type
                }
            }
        }
        
        if response.actionIdentifier == "oku" {
            if postId != ""{
                DispatchQueue.main.async(execute: {
                    NotificationCenter.default.post(name: NSNotification.Name("Detail"), object: nil, userInfo: ["id": postId, "type": postType])
                })
                completionHandler()
            }
        }else if response.actionIdentifier == "kapat" {
            print("KAPAT")
            completionHandler()
        } else {
            if postId != ""{
                DispatchQueue.main.async(execute: {
                    NotificationCenter.default.post(name: NSNotification.Name("Detail"), object: nil, userInfo: ["id": postId, "type": postType])
                })
                completionHandler()
            }
        }
    }
    
}
导入UIKit
导入CoreData
进口火基
进口谷歌手机
输入一个信号
导入用户通知
导入SDWebImageWebPCoder
@UIApplicationMain
类AppDelegate:UIResponder、UIApplicationLegate、OSPermissionObserver、OSSubscriptionObserver{
变量窗口:UIWindow?
var shortcutItemToProcess:UIApplicationShortcutItem?
func应用程序(application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.launchOptions键:任意]?)->Bool{
//应用程序启动后自定义的覆盖点。
FirebaseApp.configure()
GADMobileAds.sharedInstance().start(completionHandler:nil)
让onesignalInitSettings=[kOSSettingsKeyAutoPrompt:false,KosSettingsKeyApplaunchUrl:false]
OneSignal.initWithLaunchOptions(启动选项,
appId:“我的钥匙在这里”,
HandleNotification操作:无,
设置:onesignalInitSettings)
OneSignal.inFocusDisplayType=OSNotificationDisplayType.notification
OneSignal.promptForPushNotifications(用户响应:{在中接受
打印(“用户接受的通知:\(已接受)”)
})
//将AppDelegate添加为OBS服务器
OneSignal.add(自身作为OSPermissionObserver)
OneSignal.add(作为OSSubscriptionObserver的自身)
registerForPushNotifications()
让WebPCoder=SDImageWebPCoder.shared
SDImageCoderManager.shared.addCoder(WebPCoder)
返回真值
}
func registerForPushNotifications(){
let notificationCenter=unuservificationcenter.current()
notificationCenter.delegate=self
让readAction=UNNotificationAction(标识符:“oku”,标题:“Haberi oku”,选项:[.前台])
let closeAction=UNNotificationAction(标识符:“kapat”,标题:“kapat”,选项:[])
let category=UNNotificationCategory(标识符:“etkilesim”,操作:[readAction,closeAction],意图标识符:[],选项:[]
notificationCenter.setNotificationCategories([类别])
}
func onOSPermissionChanged(uStateChanges:OSPermissionStateChanges!){
如果stateChanges.from.status==OSNotificationPermission.notDetermined{
如果stateChanges.to.status==OSNotificationPermission.authorized{
打印(“感谢您接受通知!”)
}如果stateChanges.to.status==OSNotificationPermission.denied,则为else{
打印(“不接受通知。您可以稍后在iOS设置下打开通知。”)
}
}
}
func onSubscriptionChanged(uStateChanges:OSSubscriptionStateChanges!){
如果!stateChanges.from.subscribed&&stateChanges.to.subscribed{
打印(“已订阅OneSignal推送通知!”)
}
}
//MARK:UISceneSession生命周期
func应用程序(uApplication:UIApplication,用于连接的配置SceneSession:UISceneSession,选项:UIScene.ConnectionOptions)->UISceneConfiguration{
//在创建新场景会话时调用。
//使用此方法可以选择配置以创建新场景。
//获取要在场景中使用的shortcutItem的引用
如果让shortcutItem=options.shortcutItem{
shortcutItemToProcess=shortcutItem
}
返回UISceneConfiguration(名称:“默认配置”,会话角色:ConnectionSceneSession.role)
}
func应用程序(application:UIApplication,didDiscardSceneSessions sceneSessions:Set){
//当用户放弃场景会话时调用。
//如果在应用程序未运行时丢弃了任何会话,则将在application:didFinishLaunchingWithOptions后不久调用该会话。
//使用此方法释放特定于被丢弃场景的任何资源,因为它们不会返回。
}
扩展AppDelegate:UNUserNotificationCenterDelegate{
func userNotificationCenter(center:UNUserNotificationCenter,willPresent通知:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions)->Void){
completionHandler([.alert,.sound])
}
func userNotificationCenter(center:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,withCompletionHandler completionHandler:@escaping()->Void){
var postId:String=“”
var postType:String=“”
如果让custom=response.notification.request.content.userInfo[“custom”]as?NSDictionary{
如果让a=custom[“a”]as?NSDictionary{
如果让id=a[“id”]作为字符串{
postId=id
}
如果let type=a[“权限”]作为字符串{
postType=类型
}
}
}
如果response.actionIdentifier==“oku”{
如果已发布!=“”{
DispatchQueue.main.async(执行:{
NotificationCenter.default.post(名称:NSNotification.name(“详细”),对象:nil,用户信息:[“id”:posted,“type”:postType])
})
完成手