IOS 当应用程序在 swift 中未 运行 时收到来自 google GCM 的推送通知

IOS receive push notification from google GCM when app not running in swift

我正在使用 iOS 9.2 和 swift 2 我使用 google GCM 从 php 服务器向 iOS 用户发送通知 当应用程序在前台或后台时一切正常,但当应用程序不再 运行 时,通知没有出现

这是我的服务器端代码

$access_key =  'access_key';
$registrationIdsIOS = ["registrationIdsIOS"] ; 

// prep the bundle
$msg = array
(
    'message'   => 'message',
    'title'     => 'title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);
$fields = array
(
    'registration_ids'  => $registrationIdsIOS,
    'data'          => $msg,
    'content_available' => true

);

$headers = array
(
    'Authorization: key=' . $access_key,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result; 

这是我的 IOS 一方

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        // [START_EXCLUDE]
        // Configure the Google context: parses the GoogleService-Info.plist, and initializes
        // the services that have entries in the file
        var configureError:NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")
        gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID

        // Register for remote notifications
        if #available(iOS 8.0, *) {
            let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        } else {
            // Fallback
            let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
            application.registerForRemoteNotificationTypes(types)
        }


        // [END register_for_remote_notifications]
        // [START start_gcm_service]
        let gcmConfig = GCMConfig.defaultConfig()
        gcmConfig.receiverDelegate = self
        GCMService.sharedInstance().startWithConfig(gcmConfig)
        // [END start_gcm_service]


        UIApplication.sharedApplication().applicationIconBadgeNumber = 0

        if launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] != nil{

            let now = NSDate()
            let prefs = NSUserDefaults.standardUserDefaults()
            let notification = UILocalNotification()
            notification.alertBody = "test"
            //notification.alertTitle = userInfo["title"] as? String
            notification.alertTitle = "app name"
            notification.alertAction = "open"
            notification.fireDate = now
            notification.soundName = prefs.objectForKey("ton") as? String
            notification.userInfo = ["id":"id"]
            UIApplication.sharedApplication().scheduleLocalNotification(notification)

        }

        return true
    }


    func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
        deviceToken: NSData ) {
            // [END receive_apns_token]
            // [START get_gcm_reg_token]
            // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
            let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
            instanceIDConfig.delegate = self
            // Start the GGLInstanceID shared instance with that config and request a registration
            // token to enable reception of notifications
            GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
            registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
                kGGLInstanceIDAPNSServerTypeSandboxOption:true]
            GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
                scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
            // [END get_gcm_reg_token]


    }


    // [START receive_apns_token_error]
    func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
        error: NSError ) {
            print("Registration for remote notification failed with error: \(error.localizedDescription)")
            // [END receive_apns_token_error]
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                registrationKey, object: nil, userInfo: userInfo)
    }


    func registrationHandler(registrationToken: String!, error: NSError!) {
        if (registrationToken != nil) {
            self.registrationToken = registrationToken
            print("Registration Token: \(registrationToken)")

            let prefs = NSUserDefaults.standardUserDefaults()

            if (prefs.objectForKey("notificationRegId") as? String) != registrationToken{

                self.sendToken(registrationToken)
                prefs.setValue(registrationToken as String, forKey: "notificationRegId")
                prefs.synchronize()
            }


            //self.subscribeToTopic()
            let userInfo = ["registrationToken": registrationToken]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        } else {
            print("Registration to GCM failed with error: \(error.localizedDescription)")
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        }
    }


    func sendToken(token:String){

        if token == ""{
          print("there is no token to send to server")
        }else{
           //send token to server
        }



    }


    // [START ack_message_reception]
    func application( application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
            print("Notification received: \(userInfo)")
            // This works only if the app started the GCM service


            let now = NSDate()
            let prefs = NSUserDefaults.standardUserDefaults()
            let notification = UILocalNotification()
            notification.alertBody = userInfo["gcm.notification.message"] as? String
            //notification.alertTitle = userInfo["title"] as? String
            notification.alertTitle = "app name"
            notification.alertAction = "open"
            notification.fireDate = now
            notification.soundName = prefs.objectForKey("ton") as? String
            notification.userInfo = ["id":"id"]
             UIApplication.sharedApplication().scheduleLocalNotification(notification)
            UIApplication.sharedApplication().applicationIconBadgeNumber += 1
            GCMService.sharedInstance().appDidReceiveMessage(userInfo);
            // Handle the received message
            // [START_EXCLUDE]
            NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                userInfo: userInfo)
            // [END_EXCLUDE]
    }


    func application( application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
        fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
            print("Notification received: \(userInfo)")

            // This works only if the app started the GCM service
            GCMService.sharedInstance().appDidReceiveMessage(userInfo);
            // Handle the received message
            // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
            // [START_EXCLUDE]

            let now = NSDate()
            let prefs = NSUserDefaults.standardUserDefaults()
            let notification = UILocalNotification()
            notification.alertBody = userInfo["gcm.notification.message"] as? String
            //notification.alertTitle = userInfo["title"] as? String
            notification.alertTitle = "app name"
            notification.alertAction = "open"
            notification.fireDate = now
            notification.soundName = prefs.objectForKey("ton") as? String
            notification.userInfo = ["id":"id"]
            UIApplication.sharedApplication().scheduleLocalNotification(notification)
            UIApplication.sharedApplication().applicationIconBadgeNumber += 1
            NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                userInfo: userInfo)
            handler(UIBackgroundFetchResult.NoData);
            // [END_EXCLUDE]
    }



    // [START on_token_refresh]
    func onTokenRefresh() {
        // A rotation of the registration tokens is happening, so the app needs to request a new token.
        print("The GCM registration token needs to be changed.")
        GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
            scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
    }
    // [END on_token_refresh]

    // [START upstream_callbacks]
    func willSendDataMessageWithID(messageID: String!, error: NSError!) {
        if (error != nil) {
            // Failed to send the message.
        } else {
            // Will send message, you can save the messageID to track the message
        }
    }

    func didSendDataMessageWithID(messageID: String!) {
        // Did successfully send message identified by messageID
    }
    // [END upstream_callbacks]

    func didDeleteMessagesOnServer() {
        // Some messages sent to this device were deleted on the GCM server before reception, likely
        // because the TTL expired. The client should notify the app server of this, so that the app
        // server can resend those messages.
    }



    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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        GCMService.sharedInstance().disconnect()
        // [START_EXCLUDE]
        self.connectedToGCM = false
        // [END_EXCLUDE]

    }

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

    func applicationDidBecomeActive(application: UIApplication) {
        // Connect to the GCM server to receive non-APNS notifications
        GCMService.sharedInstance().connectWithHandler({
            (NSError error) -> Void in
            if error != nil {
                print("Could not connect to GCM: \(error.localizedDescription)")
            } else {
                self.connectedToGCM = true
                print("Connected to GCM")
                // [START_EXCLUDE]
                self.subscribeToTopic()
                // [END_EXCLUDE]
            }
        })

    }

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

iOS 的有效载荷有点不同。结构应遵循格式

{
  "content_available":true, 
  "to":"gcm_token_of_the_device",
  "priority":"high",
  "notification":
    {
      "body":"anything",
      "title":"any title"
    }
}

注意: Content_available 应为真且优先级应为高,则只有您收到通知。当您的应用处于关闭状态时