GCM for iOS,永远不会调用gcm连接处理程序

时间:2015-09-21 07:43:49

标签: ios swift google-cloud-messaging

我在我的应用程序中实施Google Cloud Messaging。我已经按照谷歌文档中提供的tutorial进行了操作。我可以通过HTTP POST请求向我的设备发送通知,但问题是在applicationDidBecomeActive中,正如谷歌所示,我尝试连接gcmService但从不调用connectionHandler块

我的AppDelegate中的

applicationDidBecomeActive函数

<Triggers>
              <asp:PostBackTrigger ControlID="btnCreate" />
           </Triggers>

有人解决了这个问题吗?

编辑 - 这是正确的方法

这是我完整的AppDelegate.swift文件

func applicationDidBecomeActive(application: UIApplication) {


    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")

            self.subscribeToTopic()
        }
    })
}

2 个答案:

答案 0 :(得分:1)

您是否检查过您的plist中已定义的NSAppTransportSecurity密钥。enter image description here

答案 1 :(得分:1)

您的代码中存在几个问题。

首先,您需要在GCMService.sharedInstance().startWithConfig(GCMConfig.defaultConfig())方法中调用didFinishLaunchingWithOptions,但只能在didRegisterForRemoteNotificationsWithDeviceToken方法中调用它。

其次,您应该在application.registerForRemoteNotifications()方法application.registerUserNotificationSettings()之后致电didFinishLaunchingWithOptions

sample GCM project for iOS可用,您可以关注AppDelegate.swift pod try Google文件,以便您的应用正常运行。

您也可以通过didFinishLaunchingWithOptions通过Cocoapods获取GCM iOS示例项目,您可以访问sample implementation了解更多详情。

编辑:

您应该使用以下内容替换let gcmConfig = GCMConfig.defaultConfig()中的行(请注意您应使用gcmConfig.receiverDelegate = self // [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 // [END_EXCLUDE] // Register for remote notifications let settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: [.Alert, .Badge, .Sound], categories: nil ) application.registerUserNotificationSettings( settings ) application.registerForRemoteNotifications() // [END register_for_remote_notifications] // [START start_gcm_service] var gcmConfig = GCMConfig.defaultConfig() gcmConfig.receiverDelegate = self GCMService.sharedInstance().startWithConfig(gcmConfig) // [END start_gcm_service] return true ):

grunt copy