2016-06-30 10 views
2

Ich habe eine iOS-App mit Swift erstellt und ich versuche, Remote-Push-Benachrichtigungen mit GCM zu erhalten. Ich habe alle Schritte zur Konfiguration von Push-Benachrichtigungen mit Google Cloud Messaging durchgeführt. Ich kann mich bei GCM registrieren und ein Token erhalten. Ich kann dann lokale Push-Benachrichtigungen (die App ist offen) an das iOS-Gerät senden. Ich versuche, die App Benachrichtigungen erhalten, wenn es in der Nähe ist.Swift Remote-Push-Benachrichtigungen mit GCM

Unten ist mein Quellcode für App.

class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate { 
    var window: UIWindow? 

    var connectedToGCM = false 
    var subscribedToTopic = false 
    var gcmSenderID: String? 
    var registrationToken: String? 
    var registrationOptions = [String: AnyObject]() 

    let registrationKey = "onRegistrationCompleted" 
    let messageKey = "onMessageReceived" 
    let subscriptionTopic = "/topics/global" 


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
    [NSObject: AnyObject]?) -> Bool { 

    var configureError:NSError? 
    GGLContext.sharedInstance().configureWithError(&configureError) 
    assert(configureError == nil, "Error configuring Google services: \(configureError)") 
    gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID 
    print(gcmSenderID) 

    if #available(iOS 8.0, *) { 
     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
     application.registerForRemoteNotifications() 
    } else { 
     let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound] 
     application.registerForRemoteNotificationTypes(types) 
    } 


    let gcmConfig = GCMConfig.defaultConfig() 
    gcmConfig.receiverDelegate = self 
    GCMService.sharedInstance().startWithConfig(gcmConfig) 

    return true 
} 


func applicationDidBecomeActive(application: UIApplication) { 
    // Connect to the GCM server to receive non-APNS notifications 
    GCMService.sharedInstance().connectWithHandler({(error:NSError?) -> Void in 
     if let error = error { 
      print("Could not connect to GCM: \(error.localizedDescription)") 
     } else { 
      self.connectedToGCM = true 
      print("Connected to GCM") 
     } 
    }) 
} 

func applicationDidEnterBackground(application: UIApplication) { 
    print("enter background") 
    GCMService.sharedInstance().disconnect() 
    self.connectedToGCM = true 
} 

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken 
    deviceToken: NSData) { 
    let instanceIDConfig = GGLInstanceIDConfig.defaultConfig() 
    instanceIDConfig.delegate = self 
    GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig) 
    registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken, 
          kGGLInstanceIDAPNSServerTypeSandboxOption:true] 
    GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, 
                  scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) 
} 

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError 
    error: NSError) { 

    print("Registration for remote notification failed with error: \(error.localizedDescription)") 

    let userInfo = ["error": error.localizedDescription] 
    NSNotificationCenter.defaultCenter().postNotificationName(
     registrationKey, object: nil, userInfo: userInfo) 

} 

func application(application: UIApplication, 
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { 

    print("Notification received: \(userInfo)") 

    GCMService.sharedInstance().appDidReceiveMessage(userInfo); 
    NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) 

    let notification = UILocalNotification() 
    notification.fireDate = NSDate() 
    notification.alertBody = "\(userInfo)" 
    notification.alertAction = "Measurz" 

    UIApplication.sharedApplication().scheduleLocalNotification(notification) 

} 

func application(application: UIApplication, 
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) { 
    print("Notification received: \(userInfo)") 

    GCMService.sharedInstance().appDidReceiveMessage(userInfo); 
    NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) 

    handler(UIBackgroundFetchResult.NoData); 

} 


func registrationHandler(registrationToken: String!, error: NSError!) { 
    if (registrationToken != nil) { 
     self.registrationToken = registrationToken 
     print("Registration Token: \(registrationToken)") 
     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 onTokenRefresh() { 
    print("The GCM registration token needs to be changed.") 
    GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, 
                  scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) 
} 


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 
} 

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. 
} 

}

Ich bemerke, dass didReceiveRemoteNotification userinfo: [NSObject: ANYOBJECT] funktioniert nur mit lokalen Push-Benachrichtigungen und wenn die Anwendung geschlossen wird diese Funktion sollte den Hintergrundprozess und das Senden der Benachrichtigung werden Handhabung: func Anwendung (Anwendung: UIApplication, didReceiveRemoteNotification userInfo: [NSObjekt: AnyObject], fetchCompletionHandler-Handler: (UIBackgroundFetchResult) -> Void), aber nichts wird auf dem Telefon angezeigt.

Unten ist ein Beispiel für die Daten, die ich über node.js

var json = { 
"registration_ids":["p0xcEUg5TYLbz-w2iuoOq3-2i4OCn_wPWpxHXU9SNxemCk9MY-kHU2Kyos5kI7_pUqXgHz8ef_BWqY4NgLTfTK1ppQE"], 
"data":{ 
    "aps" : { 
     "alert" : { 
      "title" : "Message", 
      "body" : "Please check your monthly budget", 
     } 
    } 
} 

zu GCM sende};

Jede Hilfe würde sehr geschätzt werden.

+0

Es scheint, Sie haben ein ähnliches Problem mit diesem [SO-Thread] (http://stackoverflow.com/questions/31109514/making-gcm-work-for-ios-device-in-the-background). Hör zu. – noogui

Antwort

1

Dies wurde nicht im Hintergrund auf iOS zu den gesendeten Daten empfangen.

0

Vergewissern Sie sich, dass Sie die Hintergrundmodi in den Projektfunktionen aktiviert und die Option "Remote Notifications" ausgewählt haben.