IOS получает push-уведомление от Google GCM, когда приложение не работает в swift

Я использую iOS 9.2 и Swift 2
и я использую Google GCM для отправки уведомлений с php-сервера пользователям iOS
все в порядке, когда приложение на переднем плане или в фоновом режиме, но когда приложение больше не работает, уведомление не появляется

это мой код на стороне сервера

$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 servicelet 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

Решение

Полезная нагрузка для iOS немного отличается. Структура должна быть следующего формата

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

Замечания: Content_available должно быть истинным, а приоритет должен быть высоким, тогда только вы получили уведомление. когда ваше приложение находится в закрытом состоянии

0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]