【问题标题】:iOS swift - Open notifications on specific view controlleriOS swift - 在特定视图控制器上打开通知
【发布时间】:2020-11-29 23:44:57
【问题描述】:

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

推送通知管理器:

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()
    }
}

视图控制器:

...

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

【问题讨论】:

  • 您是在使用故事板还是以编程方式创建视图控制器?
  • @phoenixroy 故事板

标签: ios swift swift3 push-notification apple-push-notifications


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    window 对象有一个 rootViewController 属性,它可以访问堆栈中最底层的视图控制器。根视图控制器是我们从 AppDelegate 访问视图控制器的入口点。

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

    只需在情节提要中为视图控制器添加情节提要 ID

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

    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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多