簡體   English   中英

當用戶點擊 iOS Swift 中的通知時,如何加載 viewController?

[英]How to load viewController when user tap on notification in iOS Swift?

我已經在應用程序端使用 FCM 完成了推送通知。 當用戶點擊通知時,它會從應用程序端導航到特定的 viewController 到自定義 SDK。 我嘗試了很多方法,但 viewController 沒有顯示,但所有功能都已成功加載。

1.第一次嘗試: [Notification tap is detected 並將數據從應用端傳遞到框架。 加載了特定的 viewController 功能,但 viewController 沒有顯示。]

當用戶從應用端點擊通知時,它將向框架發送數據以顯示特定的 viewController。

這是應用程序端的代碼:

   func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {

    
    
    
    if(application.applicationState == .active){
      print("user tapped the notification bar when the app is in foreground")
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print("didReceive notification tapped",userInfo)

        TaskName = userInfo[taskName] as? String ?? ""
        print("TaskName::::", TaskName ?? "")
        ProcessInstanceId = userInfo[processInstanceId] as? String ?? ""
        print("ProcessInstanceId::::", ProcessInstanceId ?? "")
        processDefinitionName = userInfo[ProcessDefinitionId] as? String ?? ""
        print("processDefinitionName::::", processDefinitionName ?? "")
        TaskID = userInfo[taskId] as? String ?? ""
        print("taskID::::", TaskID ?? "")
        FormKey = userInfo[formKey] as? String ?? ""
        print("FormKey::::", FormKey ?? "")
        Types = userInfo[type] as? String ?? ""
        print("Type::::", Types ?? "")
        Title = userInfo[title] as? String ?? ""
        print("Title::::", Title ?? "")
        Body = userInfo[body] as? String ?? ""
        print("Body::::", Body ?? "")
        CreatedDate = userInfo[created] as? String ?? ""
        print("created:::", CreatedDate ?? "")




        AFlowBuilder(self).callFormView(taskName: TaskName ?? "", processInstanceID: ProcessInstanceId ?? "", ProcessDefinitionName: processDefinitionName ?? "", taskId: TaskID ?? "", formKey: FormKey ?? "", title: Title ?? "", type: Types ?? "", body: Body ?? "", created: CreatedDate ?? "", formStatus: false)


    }
    completionHandler()
    
    
  }

這是框架方面的代碼:

  private var taskViewNew: UIViewController?

    public func callFormView(taskName: String, processInstanceID: String, ProcessDefinitionName: String, taskId: String, formKey: String, title: String, type: String, body: String, created: String, formStatus: Bool){
    

    
    let newNotification = makeSaveNotification(taskName: taskName, processInstanceID: processInstanceID, ProcessDefinitionName: ProcessDefinitionName, taskId: taskId, formKey: formKey, title: title, type: type, body: body, created: created, formStatus: formStatus)
    
    let realm = try! Realm()
    //        let realmData = realm.objects(NotificationRealmModel.self).filter("name = \(userNameRealm ?? "")").first!

            try! realm.write {
                realm.add(newNotification)
                print("ream notification saved path url:: call form view", realm.configuration.fileURL ?? "")



}

                    let controller = CreateCardViewController()
    
                    let str = formKey
                    let result = String(str.dropFirst(7))
                    print(result)
                    let s = String(result.dropLast(10))
                    print("newFormKey call form view", s )
                    let v = convap(text: s)
                    controller.processInstanceId = processInstanceID
                    controller.cardName = ""
                    controller.TaskIdValue = taskId
                    controller.formKey = v
                    controller.tabName = "NotificationTapped"
                    controller.fullFormKey = formKey
                    
                
                    self.taskViewNew?.addChild(controller)
                    self.taskViewNew?.view.addSubview(controller.view)
                    controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

  //                        controller.didMove(toParent: taskViewNew)
                    taskViewNew?.present(controller, animated: true, completion: nil)

                    
                    

}
  1. 第二次嘗試:[在應用程序端檢測到通知並將值傳遞給 viewController。 並且,調用內部 viewController 框架方法來加載框架 viewController 但所有功能都已成功加載但未加載視圖]

這是應用程序端的代碼:

       func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {

    
    
    
    if(application.applicationState == .active){
      print("user tapped the notification bar when the app is in foreground")
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print("didReceive notification tapped",userInfo)

        TaskName = userInfo[taskName] as? String ?? ""
        print("TaskName::::", TaskName ?? "")
        ProcessInstanceId = userInfo[processInstanceId] as? String ?? ""
        print("ProcessInstanceId::::", ProcessInstanceId ?? "")
        processDefinitionName = userInfo[ProcessDefinitionId] as? String ?? ""
        print("processDefinitionName::::", processDefinitionName ?? "")
        TaskID = userInfo[taskId] as? String ?? ""
        print("taskID::::", TaskID ?? "")
        FormKey = userInfo[formKey] as? String ?? ""
        print("FormKey::::", FormKey ?? "")
        Types = userInfo[type] as? String ?? ""
        print("Type::::", Types ?? "")
        Title = userInfo[title] as? String ?? ""
        print("Title::::", Title ?? "")
        Body = userInfo[body] as? String ?? ""
        print("Body::::", Body ?? "")
        CreatedDate = userInfo[created] as? String ?? ""
        print("created:::", CreatedDate ?? "")

     }

          window = UIWindow(frame: UIScreen.main.bounds)
             let homeViewController = ViewController()
             homeViewController.Body = Body
             homeViewController.CreatedDate = CreatedDate
             homeViewController.FormKey = FormKey
             homeViewController.processDefinitionName = processDefinitionName
             homeViewController.ProcessInstanceId = ProcessInstanceId
             homeViewController.TaskID = TaskID
             homeViewController.Title = Title
             homeViewController.Types = Types
             homeViewController.view.backgroundColor = UIColor.red
             window!.rootViewController = homeViewController
             window!.makeKeyAndVisible()


      completionHandler()
    
    
  }

這是來自應用程序端的代碼 viewController,它將加載框架 viewController 方法。

嘗試1:

    override func viewDidAppear(_ animated: Bool) {
    
    let controller = CreateCardViewController()
        let str = FormKey
        let result = String(str?.dropFirst(7) ?? "")
        print(result)
        let s = String(result.dropLast(10))
        print("newFormKey call form view", s )
        let v = convap(text: s)
        controller.processInstanceId = ProcessInstanceId
        controller.cardName = ""
        controller.TaskIdValue = TaskID
        controller.formKey = v
        controller.tabName = "NotificationTapped"
        print(controller.tabName)
        controller.fullFormKey = FormKey
    add(asChildViewController: controller)
    
        
    }


      private func add(asChildViewController viewController: UIViewController) {
    // Add Child View Controller
    addChild(viewController)

    // Add Child View as Subview
    view.addSubview(viewController.view)

    // Configure Child View
    viewController.view.frame = view.bounds
    viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Notify Child View Controller
    viewController.didMove(toParent: self)
   }

嘗試:2

      override func viewDidAppear(_ animated: Bool) {

                print("Presenting next...")
     
    
    let controller = CreateCardViewController()


            let str = FormKey
            let result = String(str?.dropFirst(7) ?? "")
            print(result)
            let s = String(result.dropLast(10))
            print("newFormKey call form view", s )
            let v = convap(text: s)
            controller.processInstanceId = ProcessInstanceId
            controller.cardName = ""
            controller.TaskIdValue = TaskID
            controller.formKey = v
            controller.tabName = "NotificationTapped"
            print(controller.tabName)
            controller.fullFormKey = FormKey

         present(controller, animated: true, completion: nil)



    }

任何幫助非常感謝請...

我目前有這樣的任務,也許它有點簡單,但這是我的代碼:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    if let navigationController =  window?.rootViewController as? UINavigationController {
        navigationController.popToRootViewController(animated: false)
        if let someViewController = navigationController.storyboard?.instantiateViewController(withIdentifier: "SomeViewController") as? SomeViewController {
            navigationController.pushViewController(someViewController, animated: true)
        }
    }
}

就我而言,它運行良好,因為我將 UINavigationController 作為我的應用程序的根目錄,並且我通過它管理我的導航。 這對於確定您現在在視圖堆棧中擁有什么以及如何清除它很重要。

此外,您可以看到我使用這一行來實例化我的新 ViewController

if let someViewController = navigationController.storyboard?.instantiateViewController(withIdentifier: "SomeViewController") as? SomeViewController

但這並不重要,只要確保您的 ViewController 正確啟動即可。

祝你好運。

我使用頂視圖 controller 來呈現所需的視圖。

要獲取俯視圖 controller:

func topController() -> UIViewController  {
    if var topController = UIApplication.shared.keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {

            topController = presentedViewController
        }
        return topController
    }
    return (UIApplication.shared.keyWindow?.rootViewController)!
}

然后在收到通知時:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(userInfo)
    guard Utility.shared.userInfo != nil else { return }

    let vc : EventDetailVC = EVENTSSTORYBOARD.viewController(id: "EventDetailVC") as! EventDetailVC
    vc.eventID = event_id
    vc.eventType = EventType.Invite
    let nav = UINavigationController(rootViewController: vc)
    nav.modalPresentationStyle = .fullScreen
    self.topController().present(nav, animated: true, completion: nil)
}

請讓我知道這對你有沒有用。

使用NotificationCenter創建一個自定義NSNotification.Name並使用您的視圖控制器訂閱創建的通知名稱

NotificationCenter.default.addObserver(self, selector: #selector(openView), name: <<custom notification name>>, object: nil)

之后使用選擇器 function 您可以將所有參數傳遞給視圖 controller

@objc func openView(notification: Notification){}

並在didFinishLaunchingWithOptions使用這個發布到上述自定義通知

let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]
            if (userInfo != nil){

                DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
                        NotificationCenter.default.post(name: <<custom notification name>>, object: nil, userInfo: userInfo as! [AnyHashable : Any]?)
                }
            }

if you have multiple viewcontrollers that needs to be open you can create a base view controller class and put above code in the base class and extend the viewcontrollers by the base class

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM