2015-09-28 122 views
1

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

的后一封邮件我使用的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库中获取示例应用程序并复制所有内容与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) 
    } 

如果有人问过类似的问题,让我知道,我没能找到一个适当的描述我的情况。

在此先感谢!

+0

您的HTTP请求看起来不错。但是,您的实施与[Google示例项目](https://github.com/googlesamples/google-services/blob/master/ios/gcm/GcmExampleSwift/ViewController.swift)之间有几处不同。您应该尝试复制并粘贴该示例项目中的所有行,或者下载示例项目。 – ztan

+0

你的链接中究竟有什么需要注意显示通知?看起来主要是UI代码。根据我从Google教程中了解的情况,Appdelegate中的代码应该足以显示简单的通知? – Dan

+0

我从来没有想过,苹果会让你使用IOS上不是APNS的推送通知。 – Nanoc

回答

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值添加到您的Info.plist中的UIBackgroundModes

+0

你是上帝,这解决了我的问题。有没有办法使用fetchCompletionHandler来更新UITableView? – Dan

+0

在调用'fetchCompletionHandler'之前,你可以做任何你想要的更新。处理程序仅用于通知iOS您已完成您想要执行的任何更新。 – evanescent