2016-02-11 66 views
0

运行,我使用的是iOS 9.2和迅速的2 我用谷歌GCM发送从PHP服务器通知给iOS使用者 每一个事情是确定的,当在前台应用程序或背景但是当应用程序没有运行任何更多的通知,并没有出现IOS收到推送通知,从谷歌GCM当应用程序不迅速

这是我的服务器端代码

$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:. 
    } 
+0

[GCM通知在iOS中处于后台模式时未收到通知](http://stackoverflow.com/questions/34704736/gcm-notifications-not-receiving-when- )现在iPhone发出通知声音,但没有通知出现 –

回答

0

iOS的有效负载有点不同。结构应如下格式

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

注: Content_available应当真实,当务之急应该是高的,那么只有ürecevied通知。当你的应用程序处于关闭状态时

+0

感谢您的回放, '>'',' 'title'=>'title', 'vibrate'=>到$味精=阵列 ( '体'=> '消息', '标题'=> '标题', '振动'=> 1, '声音'=> 1, ); –

+0

谢谢它工作正常后,我改变$ msg = array ( 'message'app-is-in-background-mode-in-ios) –