使用GCM进行Swift远程推送通知

时间:2016-06-30 03:31:54

标签: ios swift push-notification google-cloud-messaging

我有一个使用swift构建的iOS应用程序,我正在尝试使用GCM接收远程推送通知。我已经完成了使用Google Cloud Messaging配置推送通知的所有步骤。我可以在GCM注册并收到令牌。然后,我可以将本地(应用程序已打开)推送通知推送到iOS设备。我正在努力让应用程序在关闭时收到通知。

以下是我的应用源代码。

    class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate {
        var window: UIWindow?

        var connectedToGCM = false
        var subscribedToTopic = false
        var gcmSenderID: String?
        var registrationToken: String?
        var registrationOptions = [String: AnyObject]()

        let registrationKey = "onRegistrationCompleted"
        let messageKey = "onMessageReceived"
        let subscriptionTopic = "/topics/global"


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

        var configureError:NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")
        gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID
        print(gcmSenderID)

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


        let gcmConfig = GCMConfig.defaultConfig()
        gcmConfig.receiverDelegate = self
        GCMService.sharedInstance().startWithConfig(gcmConfig)

        return true
    }


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

    func applicationDidEnterBackground(application: UIApplication) {
        print("enter background")
        GCMService.sharedInstance().disconnect()
        self.connectedToGCM = true
    }

    func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
        deviceToken: NSData ) {
        let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
        instanceIDConfig.delegate = self
        GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
        registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
                               kGGLInstanceIDAPNSServerTypeSandboxOption:true]
        GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
                                                                 scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
    }

    func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
        error: NSError ) {

        print("Registration for remote notification failed with error: \(error.localizedDescription)")

        let userInfo = ["error": error.localizedDescription]
        NSNotificationCenter.defaultCenter().postNotificationName(
            registrationKey, object: nil, userInfo: userInfo)

    }

    func application( application: UIApplication,
                      didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

        print("Notification received: \(userInfo)")

        GCMService.sharedInstance().appDidReceiveMessage(userInfo);
        NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo)

        let notification = UILocalNotification()
        notification.fireDate = NSDate()
        notification.alertBody = "\(userInfo)"
        notification.alertAction = "Measurz"

        UIApplication.sharedApplication().scheduleLocalNotification(notification)

    }

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

        GCMService.sharedInstance().appDidReceiveMessage(userInfo);
        NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo)

        handler(UIBackgroundFetchResult.NoData);

    }


    func registrationHandler(registrationToken: String!, error: NSError!) {
        if (registrationToken != nil) {
            self.registrationToken = registrationToken
            print("Registration Token: \(registrationToken)")
            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 onTokenRefresh() {
        print("The GCM registration token needs to be changed.")
        GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
                                                                 scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
    }


    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
    }

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



}

我注意到 didReceiveRemoteNotification userInfo:[NSObject:AnyObject] 仅适用于本地推送通知,当应用关闭时,此功能应处理后台进程并发送通知:

func application( application: UIApplication,
                      didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void)

,但手机上没有任何内容。

以下是我通过node.js

发送给GCM的数据示例
      var json = {
    "registration_ids":["p0xcEUg5TYLbz-w2iuoOq3-2i4OCn_wPWpxHXU9SNxemCk9MY-kHU2Kyos5kI7_pUqXgHz8ef_BWqY4NgLTfTK1ppQE"],
    "data":{
      "aps" : {
          "alert" : {
              "title" : "Message",
              "body" : "Please check your monthly budget",
          }
      }
    }
  };

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

在iOS的后台没有收到关于发送数据的信息。

答案 1 :(得分:0)

确保您在项目'功能'中打开'背景模式'并选中'远程通知'。