4

I'm very new to development and couldn't find much end to end support on this topic. I did what I could using firebase help page. I'm unable to receive notifications on my ios devices but FCM is working perfectly on android. Here is my appdelegate from xcode

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.applicationIconBadgeNumber = 0
        // Override point for customization after application launch.
        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)
            //FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
            UIApplication.shared.registerForRemoteNotifications()
        }

        application.registerForRemoteNotifications()

        FirebaseApp.configure()
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token1 = Messaging.messaging().fcmToken
        print("FCM token: \(token1 ?? "")")
        var request = URLRequest(url: URL(string: "http://www.myurl.com/register.php")!)
        request.httpMethod = "POST"
        let postString = "Token="+token1!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
        task.resume()
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Registration failed!")
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

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

        // custom code to handle push while app is in the foreground
        print("Handle push from foreground\(notification.request.content.userInfo)")

        let dict = notification.request.content.userInfo["aps"] as! NSDictionary
        let d : [String : Any] = dict["alert"] as! [String : Any]
        let body : String = d["body"] as! String
        let title : String = d["title"] as! String
//        print("Title:\("FOSG NOTIFICATION") + body:\(body)")
        self.showAlertAppDelegate(title: "Federation Of Safety Glass",message:body,buttonTitle:"ok",window:self.window!)

    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
        print("Handle push from background or closed\(response.notification.request.content.userInfo)")
    }

    func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
        window.rootViewController?.present(alert, animated: false, completion: nil)
    }
    // Firebase ended here

}

and this is my code from server end on php

  $tokens = array(); $mess = '';
    // queries from db to set the values of variables.
    function send_notification ($tokens, $message)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        $fields = array(
             'registration_ids' => $tokens,
             'data' => $message
            );
        $headers = array(
            'Authorization:key = **key ',
            'Content-Type: application/json'
            );
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
       $result = curl_exec($ch);           
       if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
       }
       curl_close($ch);
       return $result;
    }
    $message = array(
        "body" => $mess,
        "message" => $mess,
        "title" => "FOSG NOTIFICATION",
        "sound" => 1,
        "vibrate" => 1,
        "badge" => 1,
    );
    $t = implode('',$tokens);
    if(t != '') $message_status = send_notification($tokens, $message);

Please help me learn and resolve my issue

5
  • Check out this Quickstart: github.com/firebase/quickstart-ios/tree/master/messaging it helped me set up messaging. Then try sending a message from the Firebase console and make sure that works. That will help narrow down if the issue is with the Swift code or the PHP. Commented Sep 29, 2017 at 17:21
  • Thank you for your reply Jen. I couldn't find the error using the github source provided by you. But Firebase console is successfully sending the notifications, it is only when I send them through my server script, I don't receive anything. Commented Sep 29, 2017 at 18:19
  • The first thing that I could think of is that you do not have the correct certificate uploaded to firebase. You could try double checking that. Commented Sep 29, 2017 at 19:27
  • Hi Daniel, i don’t know if I’m right about this, but firebase console shouldn’t be sending notifications successfully if I had the wrong certificate. Commented Sep 29, 2017 at 19:29
  • Check this out: stackoverflow.com/questions/39506040/…. Maybe adding 'priority'=>'high' to array will work for you, too? Commented Sep 29, 2017 at 21:53

1 Answer 1

3

Just changed the field names before sending the json

change the following :

$fields = array(
             'registration_ids' => $tokens,
             'data' => $message
            );

to

$fields = array(
             'registration_ids' => $tokens,
             'notification' => $message,
             'priority' => 'high'
            );
Sign up to request clarification or add additional context in comments.

2 Comments

I also have similar problem, I am unable to receive data message in IOS, please confirm me that is there any predefined format for data message that I want to receive in IOS? Is there predefined keys to be used? Is it true if format is wrong then I'll not be able to receive notification?
change 'data' to 'notification' as in the code above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.