首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在iOS (Swift4)后台通过流控模块获取推送通知

如何在iOS (Swift4)后台通过流控模块获取推送通知
EN

Stack Overflow用户
提问于 2018-08-10 14:34:19
回答 3查看 5.3K关注 0票数 1

如何在后台获取推送通知?我在Swift4 iOS 11中遇到了推送通知的问题,只有当应用程序打开时,FCM才能在后台检索通知。

这是我的代码:

AppDelegate.swift

代码语言:javascript
复制
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
        
        var window: UIWindow?
        static var DEVICE_ID = String()
        
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            
            UIApplication.shared.statusBarStyle = .lightContent
            
            FirebaseApp.configure()
            
            if #available(iOS 10.0, *) {
                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.current().delegate = self
                
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (success, error) in
                    print(success)
                })
                
                Messaging.messaging().delegate = self
                
            } else {
                let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }
            
            application.registerForRemoteNotifications()
            
            return true
        }
        
        func connectToFcm() {
            Messaging.messaging().shouldEstablishDirectChannel = true
            
            if let token = InstanceID.instanceID().token() {
                AppDelegate.DEVICE_ID = token
                print("*********")
                print("Token Instance: \(token)")
                print("*********")
            }
        }
        
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            
            completionHandler([.alert, .sound])
            
        }
        
        func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
            connectToFcm()
        }
        
        func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
            
            guard let data: [String: Any] = remoteMessage.appData as? [String: Any] else {
                return
            }
            
            print(data)
            
         
        }
        
        func applicationDidBecomeActive(_ application: UIApplication) {
            UIApplication.shared.applicationIconBadgeNumber = 0
            connectToFcm()
        }
        
        func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            
            
            completionHandler(.newData)
            
        }
        
        
    }

Example: image send push notification with postman

EN

回答 3

Stack Overflow用户

发布于 2018-08-14 15:44:07

以下是AppDelegate.swift中的源代码:

代码语言:javascript
复制
import UIKit
import UserNotifications
import FirebaseCore
import FirebaseMessaging
import FirebaseInstanceID

struct DataNotif: Codable {
    var title: String?
    var body: String?

    private enum CodingKeys: String, CodingKey {
        case title
        case body
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "message_id"

    static var DEVICE_ID = String()
    var msg_body = ""
    var msg_title = ""

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UIApplication.shared.statusBarStyle = .lightContent

        FirebaseApp.configure()

        Messaging.messaging().delegate = self

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        return true
    }

    func connectToFcm() {
        Messaging.messaging().shouldEstablishDirectChannel = true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        if let refreshedToken = InstanceID.instanceID().token() {
            AppDelegate.DEVICE_ID = refreshedToken
            print("*********")
            print("InstanceID token: \(refreshedToken)")
            print("*********")
        }else{
            print("Can't get token device")
        }

        connectToFcm()

    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications with error: \(error)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        print(userInfo)

        guard let data: [String: Any] = userInfo as? [String: Any] else {
            return
        }

        let listData = data["notification"] as! String
        let jsonData = listData.data(using: .utf8)
        do {
            let decoder = JSONDecoder()
            let dataJson = try decoder.decode(DataNotif.self, from: jsonData!)

            msg_body = dataJson.body!
            msg_title = dataJson.title!

            createNotification(title: msg_title, body: msg_body)

        }catch{
            print("error")
        }

        completionHandler(.newData)
    }

    // messaging
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {

        if let token = InstanceID.instanceID().token() {
            AppDelegate.DEVICE_ID = token
            print("*********")
            print("Token Instance: \(token)")
            print("*********")
        }

        connectToFcm()
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

        print("Received data message: \(remoteMessage.appData)")

        guard let data: [String: Any] = remoteMessage.appData as? [String: Any] else {
            return
        }

        print(data)

        let listData = data["notification"] as! String
        let jsonData = listData.data(using: .utf8)
        do {
            let decoder = JSONDecoder()
            let dataJson = try decoder.decode(DataNotif.self, from: jsonData!)

            msg_body = dataJson.body!
            msg_title = dataJson.title!

            createNotification(title: msg_title, body: msg_body)

        }catch{
            print("error")
        }

    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler([.alert, .badge, .sound])
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
        connectToFcm()
    }

    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        if let vc = window?.rootViewController as? HomeController {
            vc.scheduleNotification()
        }

        completionHandler(.newData)

    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        Messaging.messaging().shouldEstablishDirectChannel = false
        print("Disconnect FCM")
    }

    func createNotification(title: String, body: String) {
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil)
        content.sound = UNNotificationSound.default()
        content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)

        let request = UNNotificationRequest.init(identifier: "pushNotif", content: content, trigger: nil)

        let center = UNUserNotificationCenter.current()
        center.add(request)
    }

}
票数 2
EN

Stack Overflow用户

发布于 2019-01-14 17:09:32

Firebase为推送通知提供后台和前台支持。您可以通过以下步骤轻松解决您的问题:

AppDelegate.swift导入firebase库中的

代码语言:javascript
复制
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications

每当应用程序启动注册推送通知服务时,请在您的didFinishLaunchingWithOptions中添加以下代码行

代码语言:javascript
复制
 func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        registerForPushNotifications(application: application)
        return true
    }

添加appDelegate的扩展方法以注册远程通知并从APNS获取设备令牌

代码语言:javascript
复制
       extension AppDelegate {
         func registerForPushNotifications(application: UIApplication) {
             if #available(iOS 10.0, *) {
                    // For iOS 10 display notification (sent via APNS)
                     UNUserNotificationCenter.current().delegate = self
                    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
                    UNUserNotificationCenter.current().requestAuthorization(
                    options: authOptions,
                    completionHandler: {_, _ in })
                    // For iOS 10 data message (sent via FCM
                   Messaging.messaging().delegate = self
               } else {
                   let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }

            application.registerForRemoteNotifications()
        }
      func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        let savedAPNSToken = UserDefaults.standard.object(forKey: "savedAPNSToken") as? String
        if savedAPNSToken != token {
            UserDefaults.standard.set(token, forKey: "savedAPNSToken")
            UserDefaults.standard.synchronize()
            Messaging.messaging().apnsToken = deviceToken
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error.localizedDescription)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        completionHandler(UIBackgroundFetchResult.newData)
    }
}

使用notificationCenter的以下方法在前台和后台状态处理通知:

代码语言:javascript
复制
// MARK: - UNUserNotificationCenterDelegate
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        completionHandler([.alert])
    }


    /// Handle tap on the notification banner
    ///
    /// - Parameters:
    ///   - center: Notification Center
    ///   - response: Notification response
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

防火墙令牌更新:

代码语言:javascript
复制
// MARK: - MessagingDelegate
extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        // Note: This callback is fired at each app startup and whenever a new token is generated.
        let savedFCMToken = UserDefaults.standard.object(forKey: "savedFCMToken") as? String
        if savedFCMToken != fcmToken {
            UserDefaults.standard.set(fcmToken, forKey: "savedFCMToken")
            UserDefaults.standard.synchronize()
            // Update FCMToken to server by doing API call...
        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2018-08-10 17:26:05

我不能找出你的代码中的问题,但我发布了应该如何完成的步骤:

应用程序应用程序注册推送通知应用程序(_

  1. :UIApplication,didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any?) -> Bool {

FirebaseApp.configure() self.registerForPushNotifications(application)返回true }函数应用程序(_registerForPushNotifications: UIApplication){ Messaging.messaging().delegate = self if #available(iOS 10,*) {

让center = UNUserNotificationCenter.current() center.requestAuthorization(options:.badge,.alert,.sound) { (granted,error) in //根据授权开启或关闭功能。} center.delegate=self application.registerForRemoteNotifications() } else{ let application.registerForRemoteNotifications=UIUserNotificationSettings(类型:.alert,.badge,.sound,类别: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } }

2.然后处理你的委托:

代码语言:javascript
复制
func application(_ application: UIApplication, 

    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            Messaging.messaging().apnsToken = deviceToken

        }

  1. 处理您的Firebase消息传递委派:-

扩展消息: MessagingDelegate { func messaging(_ messaging: Messaging,didReceiveRegistrationToken fcmToken: String) {

let token = fcmToken //您可以将token发送到服务器,从服务器获取推送通知}

}

4.然后处理你的UNUserNotificationCenterDelegate:

代码语言:javascript
复制
   func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // this is called when application is Foreground and push arrives we show alert, sound, here.
                completionHandler([.alert, .sound])

            }
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void){
            let pushDictionary = response.notification.request.content.userInfo
         // handle your push here
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51780379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档