Search code examples
iosswiftfirebasealertfirebase-notifications

How to show alert after user tap firebase notification in swift?


I've issue when user tap firebase notification in ios. When user tap the notification, I redirect the user to specific function. It success accessing the function but can't show the alert that I define. This is my code :

AppDelegate.swift

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler:  @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    if(String(describing: userInfo) != "[:]"){
        print("userInfo : \(userInfo)")
        print("firebase 3")

        var userData = userInfo as NSDictionary? as? [AnyHashable: AnyObject] ?? [:]
        let responseAlert = (userData["aps"]! as! NSDictionary)["alert"]! as! NSDictionary
        let title = responseAlert["title"]! as! String
        if(title == "x"){
            viewController.x()
        }
    }

    completionHandler()
}

ViewController.swift

func x(){
    let a = (UserDefaults.standard.string(forKey: "a"))!
    let b = (UserDefaults.standard.string(forKey: "b"))!

    if Reachability.isConnectedToNetwork() == true {
        if let url = URL(string: UrlHelper.url_x){
            let request = NSMutableURLRequest(url:url)
            request.httpMethod = "POST";
            let paramString = "&a="+a+"&b="+b

            request.httpBody = paramString.data(using: String.Encoding.utf8)
            var responseString: NSString!
            let task = URLSession.shared.dataTask(with:request as URLRequest){
                data, response, error in
                if error != nil{
                    let responsealert = UIAlertController(title: "Error", message: "Service Not Available" , preferredStyle: UIAlertControllerStyle.alert)
                    responsealert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                    self.present(responsealert, animated: true, completion: nil)
                }else{
                    do {
                        if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {
                            print(convertedJsonIntoDict)
                            if (((convertedJsonIntoDict[0] as! NSDictionary)["status"] as! String)) == "0" {
                                DispatchQueue.main.async(execute: {
                                    let message = ((convertedJsonIntoDict[0] as! NSDictionary)["result"]! as! NSDictionary)["message"]! as! String
                                    let responsealert = UIAlertController(title: "Error", message: message , preferredStyle: UIAlertControllerStyle.alert)
                                    responsealert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                                    self.present(responsealert, animated: true, completion: nil)
                                })
                            }else if (((convertedJsonIntoDict[0] as! NSDictionary)["status"] as! String)) == "1" {
                                let newX = ((convertedJsonIntoDict[0] as! NSDictionary)["result"]! as! NSDictionary)["new_x"]! as! String
                                DispatchQueue.main.async(execute: {
                                    let responsealert = UIAlertController(title: "Success", message: "You got new data" , preferredStyle: UIAlertControllerStyle.alert)
                                    responsealert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                                    self.present(responsealert, animated: true, completion: nil)
                                })
                            }
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }
                }
            }
            task.resume()
        }
    }else{
        let connectionAllert = UIAlertView(title: "No Network Connection", message: "Please enable your network connection.", delegate: self, cancelButtonTitle: "OK")
        connectionAllert.show()
    }
}

I think, the problem is inside this code :

let responsealert = UIAlertController(title: "Success", message: "You got new data" , preferredStyle: UIAlertControllerStyle.alert)
responsealert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(responsealert, animated: true, completion: nil)

When I log inside the dispatch, the log is showing. When I trigger the function from clicking a button, the alert is showing.


Solution

  • Export the function x() to the AppDelegate. Than write instead of

    self.present(responsealert, animated: true, completion: nil)
    

    this:

    self.window?.rootViewController?.present(responsealert, animated: true, completion: nil)
    

    Since the AppDelegate has no view you have to use

    window?.rootViewController?