繁体   English   中英

iOS swift - 在特定视图上打开通知 controller

[英]iOS swift - Open notifications on specific view controller

当我收到通知时,我想将我的应用程序打开到特定屏幕。 目前,当用户点击通知时,应用程序只会在当前屏幕上打开,但我如何才能重定向到另一个屏幕。 请提出任何解决方案?

推送通知管理器:

import FirebaseMessaging

class PushNotificationManager: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {
    let userID: String
    
    init(userID: String) {
        self.userID = FriendSystem.system.CURRENT_USER_ID
        super.init()
    }
    
    func registerForPushNotifications() {
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
            
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })

            Messaging.messaging().delegate = self
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            
            UIApplication.shared.registerUserNotificationSettings(settings)
        }
        
        UIApplication.shared.registerForRemoteNotifications()
        
        updateFirestorePushTokenIfNeeded()
    }
    
    func updateFirestorePushTokenIfNeeded() {
        if let token = Messaging.messaging().fcmToken {
            let usersRef = FriendSystem.system.USER_REF.document(userID)
            usersRef.setData(["fcmToken": token], merge: true)
        }
    }
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        updateFirestorePushTokenIfNeeded()
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    }
}

推送通知发送者:

import Foundation

class PushNotificationSender {
    func sendPushNotification(to token: String, title: String) {
        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] = ["to" : token,
                                           "notification" : ["title" : title],
                                           "data" : ["user" : "test_id"]
        ]
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAA40aUkvQ:APA91bF-CnQ2x9eHtXyzBBymNvfy6YlFeN-uv8HVgSmX6Po7o8Ko3TEL7q4zwFPx8JiZnQI6pkYVIt2OlNevJr5-K-igKFB7439ssl_9lDm-6QKPLsLGfa0x3PsCCw5johTFh5UzcZe8", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()
    }
}

查看 controller:

...

let sender = PushNotificationSender()
sender.sendPushNotification(to: post_token!, title: "New notification!")

AppDelegate 有一个 window 属性,其中包含正在显示的所有视图控制器。

window object 有一个 rootViewController 属性,它访问堆栈中的大多数底部视图控制器。 根视图 controller 是我们从 AppDelegate 访问视图控制器的入口点。

故事板流程

假设我们想在用户点击推送通知时显示 ListViewController:

只需在 storyboard 中为视图 controller 添加 storyboard id

添加情节提要 ID

要跳转到特定视图 controller,您需要实例化目标视图 controller 并推送它

func jumpToViewController() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    // instantiate the view controller we want to show from storyboard
    // root view controller is tab bar controller (initial view controller in storyboard)
    // the selected tab is a navigation controller
    // then we push the new view controller to it
    if  let listVC = storyboard.instantiateViewController(withIdentifier: "ListViewController") as? ListViewController,
        let tabBarController = self.window?.rootViewController as? UITabBarController,
        let navController = tabBarController.selectedViewController as? UINavigationController {

            // we can modify properties of the new view controller using notification data
            // (eg: title of notification)
            listVC.title = response.notification.request.content.title
            navController.pushViewController(listVC, animated: true)
    }
}

您可以在 appdelegate 的didFinishLaunchingWithOptions方法中检查launchOptions以了解应用程序是否已通过通知启动的天气,并相应地移动到所需的视图控制器。

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

     if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
     // Move to your required viewcontroller here
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM