Skip to end of metadata
Go to start of metadata

PushNotificationService class wraps the GCM related methods for the AppDelegate object, and need to be invoked by the AppDelegate when the corresponding callbacks occur.

The following methods are available in the PushNotificationService class:

public class PushNotificationService {
    
    var connectedToGCM = false
    var subscribedToTopic = false
    var gcmSenderID: String?
    var registrationToken: String?
    var registrationOptions = [String: AnyObject]()
    var client: SonusWRTCClient?
    var appDelegate: AppDelegate?
    
    let registrationKey = "onRegistrationCompleted"
    let messageKey = "onMessageReceived"
    var userId: String?
    var deviceId: String?
    
    static let instance = PushNotificationService()
    private init() {
        
    }
    
    class func sharedInstance() -> PushNotificationService {
        return self.instance
    }
    func initialize(application: UIApplication, delegate: AppDelegate) {
        
        self.appDelegate = delegate
        // 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)
        }
        
        // Start GCM Service
        let gcmConfig = GCMConfig.defaultConfig()
        gcmConfig.receiverDelegate = delegate
        GCMService.sharedInstance().startWithConfig(gcmConfig)
    }
    
    public func registerDevice(deviceToken: NSData) {
        // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
        let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
        instanceIDConfig.delegate = self.appDelegate
        // 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)
    }
    
    public func enablePushNotification(client: SonusWRTCClient) {
        print("enablePushNotification")
        self.client = client;
        if (self.client!.isConnected()) {
            let connection = client.connection()
            self.deviceId = connection.deviceId()
            self.userId = connection.userId()
        }
        sendStartNotification()
    }
    
    public func disablePushNotification(client: SonusWRTCClient) {
        print("disablePushNotification");
        sendStopNotification()
    }
    
    public func receivedNotification(userInfo: [NSObject : AnyObject]) {
        print("Notification received: \(userInfo)")
        // This works only if the app started the GCM service
        GCMService.sharedInstance().appDidReceiveMessage(userInfo);
        NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                                                                  userInfo: userInfo)
    }
    
    public func receivedNotificationBackground(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);
        NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                                                                  userInfo: userInfo)
        handler(UIBackgroundFetchResult.NoData);
    }
    
    public func registrationFailed(application: UIApplication, 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)
    }
    
    public func applicationInBackground() {
        // [Disconnect GCM Service
        GCMService.sharedInstance().disconnect()
        self.connectedToGCM = false
    }
    
    public func applicationInForeground() {
        // 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")
            }
        })
        print("applicationDidBecomeActive ")
    }
    
    public func tokenRefresh() {
        // 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)
    }
    
    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)
            // Send the token to WRTC server
        } 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 sendStartNotification() {
        print("sendStartNotification");
        let data: [NSObject: AnyObject] = ["action": "start-notification",
                    "token": self.registrationToken!,
                    "userId": self.userId!,
                    "enterprise": "sonus",
                    "deviceId": self.deviceId!,
                    "deviceType": (self.client?.capabilities().operatingSystem())!,
                    "incomingCallNotification": "true",
                    "incomingMessageNotification": "true"]
        let messageId = NSProcessInfo.processInfo().globallyUniqueString
        let senderId = gcmSenderID! + "@gcm.googleapis.com"
        GCMService.sharedInstance().sendMessage(data, to: senderId,
                                                withId: messageId)
    }
    
    func sendStopNotification(){
        print("sendStoptNotification");
        let data: [NSObject: AnyObject] = ["action": "stop-notification",
                                           "userId": self.userId!,
                                           "enterprise": "sonus",
                                           "deviceId": self.deviceId!,
                                           "incomingCallNotification": "false",
                                           "incomingMessageNotification": "false"]
        let messageId = NSProcessInfo.processInfo().globallyUniqueString
        let senderId = gcmSenderID! + "@gcm.googleapis.com"
        GCMService.sharedInstance().sendMessage(data, to: senderId,
                                                withId: messageId)
    }
}

 

For more information on APIs supporting the Google Cloud Messaging feature, refer to Google Cloud Messaging Support APIs.


  • No labels