iOS GCM通知发送,但不显示

时间:2015-09-28 13:27:51

标签: ios swift google-cloud-messaging

我正在尝试在我的iOS应用中实施GCM。一切似乎工作正常,应用程序连接到GCM并获得注册ID。如果我使用Postman向该regid发送通知,则可以使用Google收到成功回复。但是,无论我尝试什么,通知都不会在设备上显示。

我正在使用的GCM服务器的帖子消息是

{
    "to" : "RegID",
    "content_available" : true,
    "notification" : {
        "body" : "Test Body",
        "title" : "Test Title"
    }
}

给了我回复:

{
    "multicast_id": 6594175386712804014,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1443445858075083%c4cfa24dc4cfa24d"
        }
    ]
}

这让我相信我的应用中的代码存在问题。下面我粘贴了所有相关代码。我已经编写了3次没有成功的代码,首先按照教程编辑它以适应我的应用程序,第二次我从教程中复制代码,第三次从Github repo获得示例应用程序并复制一切与GCM相关。

AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate  {

    var window: UIWindow?

    var connectedToGCM = false
    var gcmSenderID: String?
    var registrationToken: String?
    var registrationOptions = [String: AnyObject]()
    let defaults = NSUserDefaults.standardUserDefaults()

    let registrationKey = "onRegistrationCompleted"
    let messageKey = "onMessageReceived"
    let notification = "isNotificationEnabled"

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Google Cloud Messaging
        var configureError:NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")
        gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID

        var types: UIUserNotificationType = UIUserNotificationType.Badge |
            UIUserNotificationType.Alert |
            UIUserNotificationType.Sound
        var settings: UIUserNotificationSettings =
        UIUserNotificationSettings( forTypes: types, categories: nil )
        application.registerUserNotificationSettings( settings )
        application.registerForRemoteNotifications()

        var gcmConfig = GCMConfig.defaultConfig()
        GCMService.sharedInstance().startWithConfig(gcmConfig)

        return true
    }

    func applicationDidBecomeActive(application: UIApplication) {              
        GCMService.sharedInstance().connectWithHandler({
            (NSError error) -> Void in
            if error != nil {
                println("Could not connect to GCM: \(error.localizedDescription)")
            } else {
                self.connectedToGCM = true
                println("Connected to GCM")
                // ...
            }
        })

    }

    func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
        deviceToken: NSData ) {
            println(deviceToken)
            // [END receice_apns_token]
            // [START get_gcm_reg_token]
            // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
            var instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
            // 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]
    }

    func registrationHandler(registrationToken: String!, error: NSError!) {
        if (registrationToken != nil) {
            self.registrationToken = registrationToken
            println("Registration Token: \(registrationToken)")
            let userInfo = ["registrationToken": registrationToken]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        } else {
            println("Registration to GCM failed with error: \(error.localizedDescription)")
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        }
    }

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


    func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        println("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]
        NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
            userInfo: userInfo)
    }

如果有人在让我知道之前问过类似的问题,我找不到能够正确描述我情况的问题。

提前致谢!

1 个答案:

答案 0 :(得分:3)

您还没有实施适当的通知回调。你需要实现

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

   // Do something with userInfo
   // call fetchCompletionHandler with the appropriate UIBackgroundFetchResult 
}

无声推送通知(即设置了content-available标志的通知)调用上述UIApplicationDelegate方法而不是application:didReceiveRemoteNotification:

另外,请确保您已将remote-notification值添加到UIBackgroundModes中的Info.plist