Problema não registrado no GCM IOS
Estou usando o GCM há muito tempo. Um dia, de repente quebrou. O problema é que, no primeiro envio, recebo o status de sucesso, mas o aplicativo não recebe nenhum empurrão. O segundo envio enviado obtém falha com um erro NotRegistered. Eu reinstalei o aplicativo: sucesso (nenhuma notificação recebida), falha (NotRegistered) -> Loop. Não sei o que mudou. O suporte do Google está sendo muito inútil e está demorando muito para responder a uma pergunta simples, seja um problema de GCM, APNs ou cliente. Se alguém já teve esse problema antes, informe-me o que procurar. É assim que parece:
Eu suspeito que isso aconteceu após a atualização para o iOS 9. Porém, não tenho certeza. Se há coisas no novo iOS que possam estar bloqueando o GCM, eu apreciaria se alguém apontasse isso.
ATUALIZAR:
O envio do GCM falha com NotRegistered
esse cara teve um problema semelhante. O problema estava em algum arquivo de manifesto. Pode haver algumas entradas no Info.plist que preciso adicionar ao iOS 9 para permitir o GCM?
ATUALIZAR:
onTokenRefresh está sendo chamado toda vez que o aplicativo é iniciado. Estou recebendo o mesmo token de volta, no entanto. Portanto, há um problema com um token em um servidor GCM, suspeito.
CÓDIGO DELEGADO DO GCM NO APLICATIVO:
var connectedToGCM = false
private var deviceToken: NSData?
var gcmSenderID: String!
let authorizedEntity = "my GCM Sender_ID"
public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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
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()
GCMService.sharedInstance().startWithConfig(gcmConfig)
return true
}
public func onTokenRefresh() {
print("Token needs to be refreshed!")
let options = [
kGGLInstanceIDRegisterAPNSOption : deviceToken!,
kGGLInstanceIDAPNSServerTypeSandboxOption : true
]
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(authorizedEntity, scope: kGGLInstanceIDScopeGCM, options: options) { (token, error) -> Void in
if error != nil {
print("Error: \(error.localizedDescription)")
} else {
print("Token: \(token)")
}
}
}
public func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
public func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
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)
self.deviceToken = deviceToken
}
public func applicationDidEnterBackground(application: UIApplication) {
GCMService.sharedInstance().disconnect()
connectedToGCM = false
}
public func applicationDidBecomeActive( application: UIApplication) {
print("App became active")
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
// 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")
// ...
}
})
}
public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Notification received: \(userInfo)")
GCMService.sharedInstance().appDidReceiveMessage(userInfo)
}
public func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Error registering")
}
public func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("Notification received(background): \(userInfo)")
NotificationManager.sharedInsteance().parseNotification(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]
handler(UIBackgroundFetchResult.NewData);
// [END_EXCLUDE]
}
ATUALIZAR
OK, então eu acredito que errei com o local .plist (não estava na raiz por algum motivo). Mudei para a raiz e agora recebo este aviso / erro ao iniciar o GCM:
UPD. Ok, na verdade aconteceu apenas uma vez e parou. Então, eu não acho que o problema está aqui.
Depois que eu mudei .plist para o diretório raiz, as chamadas onTokenRefresh () foram interrompidas, mas ainda estou recebendo o NotRegistered.