我正在尝试在我的 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 存储库中获取示例应用程序并复制所有内容与 GCM 相关。
应用委托(delegate):
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)
}
如果有人在告诉我之前问过类似的问题,我找不到合适的问题来描述我的情况。
提前致谢!
最佳答案
您还没有实现适当的通知回调。你需要实现
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
。
关于iOS GCM 通知发送,但不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32824266/