<commit_before>/**
 * Copyright IBM Corporation 2015
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/


import UIKit
import BMSCore
import BMSSecurity
import BMSPush


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    
    /**
     Method called when app finishes up launching. In this case we initialize Bluemix Mobile Client Access with Facebook
     
     - parameter application:   UIApplication.
     - parameter launchOptions: [NSObject: Anyobject]?
     
     - returns: Bool
     */
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound]
        let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
        application.registerUserNotificationSettings(notificationSettings)
        application.registerForRemoteNotifications()
        
        preLoadKeyboardToPrevantLaggyKeyboardInCameraConfirmationScreen()
        
        BluemixDataManager.SharedInstance.getImages()
        
        return self.initializeBackendForFacebookAuth(application, launchOptions: launchOptions)
    }
    
    func application (application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
        let push =  BMSPushClient.sharedInstance
        push.registerDeviceToken(deviceToken) { (response, statusCode, error) -> Void in
            if error.isEmpty {
                print( "Response during device registration : \(response)")
                print( "status code during device registration : \(statusCode)")
            }
            else{
                print( "Error during device registration \(error) ")
                print( "Error during device registration \n  - status code: \(statusCode) \n Error :\(error) \n")
            }
        }
        
    }
    
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        print("Received notification from server")
        if let payload = userInfo["payload"], data = payload.dataUsingEncoding(NSUTF8StringEncoding) {
            do {
                let anyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
                if let dictionary = anyObject as? [String : AnyObject], image = Image(dictionary) {
                    
                    guard let tabBarController = self.window?.rootViewController as? TabBarViewController, feedNav = tabBarController.viewControllers?.first as? FeedNavigationController else {
                        return
                    }
                    print(tabBarController.viewControllers)
                    let imageDetailVC = Utils.vcWithNameFromStoryboardWithName("ImageDetailViewController", storyboardName: "Feed") as! ImageDetailViewController
                    imageDetailVC.image = image
                    tabBarController.selectedIndex = 0
                    feedNav.popToRootViewControllerAnimated(false)
                    feedNav.pushViewController(imageDetailVC, animated: true)
                }
            }
            catch {
               print("Error converting NSData to json object")
            }
        }
        completionHandler(UIBackgroundFetchResult.NewData)
    }
    
    /**
     Method preloads keyboard to prevant the keybaord on the camera confirmation screen to be laggy when touching the text field for the first time
     */
    func preLoadKeyboardToPrevantLaggyKeyboardInCameraConfirmationScreen(){
        
        let lagFreeField = UITextField()
        self.window?.addSubview(lagFreeField)
        lagFreeField.becomeFirstResponder()
        lagFreeField.resignFirstResponder()
        lagFreeField.removeFromSuperview()
        
    }
    
    
    /**
     Method to initialize Bluemix Mobile Client Access with Facebook
     */
    func initializeBackendForFacebookAuth(application: UIApplication, launchOptions: [NSObject: AnyObject]?) -> Bool {
        //Initialize backend
        BluemixDataManager.SharedInstance.initilizeBluemixAppRoute()

        //Initialize Facebook
        BMSClient.sharedInstance.authorizationManager = MCAAuthorizationManager.sharedInstance
        //IMFFacebookAuthenticationHandler.sharedInstance().registerWithDefaultDelegate()
        FacebookAuthenticationManager.sharedInstance.register()<commit_msg>created logic to handle push notifications while app is already open #130<commit_after>/**
 * Copyright IBM Corporation 2015
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/


import UIKit
import BMSCore
import BMSSecurity
import BMSPush


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    
    /**
     Method called when app finishes up launching. In this case we initialize Bluemix Mobile Client Access with Facebook
     
     - parameter application:   UIApplication.
     - parameter launchOptions: [NSObject: Anyobject]?
     
     - returns: Bool
     */
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound]
        let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
        application.registerUserNotificationSettings(notificationSettings)
        application.registerForRemoteNotifications()
        
        preLoadKeyboardToPrevantLaggyKeyboardInCameraConfirmationScreen()
        
        BluemixDataManager.SharedInstance.getImages()
        
        return self.initializeBackendForFacebookAuth(application, launchOptions: launchOptions)
    }
    
    func application (application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
        let push =  BMSPushClient.sharedInstance
        push.registerDeviceToken(deviceToken) { (response, statusCode, error) -> Void in
            if error.isEmpty {
                print( "Response during device registration : \(response)")
                print( "status code during device registration : \(statusCode)")
            }
            else{
                print( "Error during device registration \(error) ")
                print( "Error during device registration \n  - status code: \(statusCode) \n Error :\(error) \n")
            }
        }
        
    }
    
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        guard let tabBarController = self.window?.rootViewController as? TabBarViewController, feedNav = tabBarController.viewControllers?.first as? FeedNavigationController else {
            completionHandler(UIBackgroundFetchResult.Failed)
            return
        }
        
        if application.applicationState == UIApplicationState.Background || application.applicationState == UIApplicationState.Inactive {
            loadImageDetail(userInfo, tabBarController: tabBarController ,feedNav: feedNav)
        } else {
            if let aps = userInfo["aps"], category = aps["category"] as? String where category == "imageProcessed" {
                
                let alert = UIAlertController(title: NSLocalizedString("Your image was processed!", comment: ""),
                                              message: NSLocalizedString("Would you like to view your image now?", comment: ""),
                                              preferredStyle: UIAlertControllerStyle.Alert)
                
                alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
                alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (action) in
                    self.loadImageDetail(userInfo, tabBarController: tabBarController, feedNav: feedNav)
                }))
                feedNav.presentViewController(alert, animated: true, completion: nil)
            }
        }
        completionHandler(UIBackgroundFetchResult.NewData)
    }
    
    /**
     Loads image detail view for image mentioned in userInfo dictionary
     
     - parameter userInfo:         dictionary of info from a push notification
     - parameter tabBarController: primary tab bar controller for application
     - parameter feedNav:          root navigation controller for feed flow
     */
    func loadImageDetail(userInfo: [NSObject : AnyObject], tabBarController: TabBarViewController, feedNav: FeedNavigationController) {
        if let payload = userInfo["payload"] as? String, dictionary = Utils.convertStringToDictionary(payload), image = Image(dictionary) {
            
            let imageDetailVC = Utils.vcWithNameFromStoryboardWithName("ImageDetailViewController", storyboardName: "Feed") as! ImageDetailViewController
            imageDetailVC.image = image
            tabBarController.selectedIndex = 0
            feedNav.popToRootViewControllerAnimated(false)
            feedNav.pushViewController(imageDetailVC, animated: true)
        }
    }
    
    /**
     Method preloads keyboard to prevant the keybaord on the camera confirmation screen to be laggy when touching the text field for the first time
     */
    func preLoadKeyboardToPrevantLaggyKeyboardInCameraConfirmationScreen(){
        
        let lagFreeField = UITextField()
        self.window?.addSubview(lagFreeField)
        lagFreeField.becomeFirstResponder()
        lagFreeField.resignFirstResponder()
        lagFreeField.removeFromSuperview()
        
    }
    
    
    /**
     Method to initialize Bluemix Mobile Client Access with Facebook
     */
    func initializeBackendForFacebookAuth(application: UIApplication, launchOptions: [NSObject: AnyObject]?) -> Bool {
        //Initialize backend
        BluemixDataManager.SharedInstance.initilizeBluemixAppRoute()

        //Initialize Facebook
        BMSClient.sharedInstance.authorizationManager = MCAAuthorizationManager.sharedInstance
        //IMFFacebookAuthenticationHandler.sharedInstance().registerWithDefaultDelegate()
        FacebookAuthenticationManager.sharedInstance.register()
{'fraction_non_alphanumeric': 0.06860475087899837, 'fraction_numerical': 0.0018866306491724552, 'mean_word_length': 2.9305695989214695, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2961006', 'n_tokens_mistral': 2765, 'n_tokens_neox': 2674, 'n_words': 769}