Thursday, 17 December 2015

SWIFT: GENERATE DEVICE TOKEN FOR PUSHNOTIFICATIONS

GENERATE DEVICE TOKEN FOR PUSHNOTIFICATIONS IN SWIFT


IN Appdelegate.swift

create these methods:


    func initializeNotificationServices() -> Void {
        
        let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        
        // This is an asynchronous method to retrieve a Device Token
        // Callbacks are in AppDelegate.swift
        // Success = didRegisterForRemoteNotificationsWithDeviceToken
        // Fail = didFailToRegisterForRemoteNotificationsWithError
        UIApplication.sharedApplication().registerForRemoteNotifications()
    }
    
    
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let deviceTokenStr = convertDeviceTokenToString(deviceToken)
        // ...register device token with our Time Entry API server via REST
        print("dynamic Device Token:    \(deviceTokenStr)")  
    }
    
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print("Device token for push notifications: FAIL -- ")
        print(error.description)
    }


Call this function "initializeNotificationServices()" where ever you want like below

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.initializeNotificationServices()

No comments:

Setting Up Multiple App Targets in Xcode from a Single Codebase

 To create two different apps (like "Light" and "Regular") from the same codebase in Xcode, you can follow these steps b...