2016-04-19 2 views
0

в моем приложении i реализовано push-уведомление. когда мое приложение находится в запущенном состоянии, и если push-уведомление приходит, я обрабатываю это с помощью этого кода.Как открыть определенное сообщение при нажатии на push-уведомление

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

    myid = (userInfo["id"] as? String)! 
    print(myid) 
    if let notification = userInfo["aps"] as? NSDictionary, 
     let alert = notification["alert"] as? String { 
      var alertCtrl = UIAlertController(title: "Notification", message: alert as String, preferredStyle: UIAlertControllerStyle.Alert) 
      alertCtrl.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 
      // Find the presented VC... 
      var presentedVC = self.window?.rootViewController 
      while (presentedVC!.presentedViewController != nil) { 
       presentedVC = presentedVC!.presentedViewController 
      } 
      presentedVC!.presentViewController(alertCtrl, animated: true, completion: nil) 



    } 

Что я хочу :: когда мое приложение не работает, и если толчок уведомление придет я хочу открыть perticular должности на основании этого уведомления после ид. так как я могу это сделать? Вот мой код

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black) 
    UIApplication.sharedApplication().applicationIconBadgeNumber = 0 
    let dicTemp = launchOptions?["UIApplicationLaunchOptionsRemoteNotificationKey"] 
    if dicTemp != nil{ 


     window = UIWindow(frame: UIScreen.mainScreen().bounds) 
     storyboard = UIStoryboard(name: "Main", bundle: nil) 


     myid = (dicTemp["id"] as? String)! 


     let controller:pushnotificationpostViewController = self.storyboard.instantiateViewControllerWithIdentifier("pushnotificationpostViewController") as! pushnotificationpostViewController 
     navigation = UINavigationController(rootViewController: controller) 
     window?.rootViewController = navigation 
     window?.makeKeyAndVisible() 

    } 

    else 
    { 
     window = UIWindow(frame: UIScreen.mainScreen().bounds) 
     storyboard = UIStoryboard(name: "Main", bundle: nil) 
     let controller:MainViewController = self.storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController 
     navigation = UINavigationController(rootViewController: controller) 
     window?.rootViewController = navigation 
     window?.makeKeyAndVisible() 
    } 


    //print(NSUserDefaults.standardUserDefaults().valueForKey("pushnotify")as! Bool) 

    let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound] 
    let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil) 
    application.registerUserNotificationSettings(pushNotificationSettings) 


    if (NSUserDefaults.standardUserDefaults().valueForKey("pushnotify")) != nil 
    { 
     pushnotification = NSUserDefaults.standardUserDefaults().valueForKey("pushnotify") as! Bool 
     // let notificationcheck = NSUserDefaults.standardUserDefaults().valueForKey("pushnotify") as! Bool 

     if (pushnotification == true) 
     { 
      application.registerForRemoteNotifications() 
     } 
     else 
     { 
      application.unregisterForRemoteNotifications() 
     } 

    } 
    else 
    { 
     application.registerForRemoteNotifications() 
    } 


    return true 
} 

но этот код я не получаю идентификатор означает MyID получает ноль. так как я могу это сделать?

+0

Ваш код работает, когда приложение запущено? –

+0

да, его работа, когда приложение работает @ SuhasPatil –

ответ

1

я думаю, что при выходе из приложения метод didReceiveRemoteNotification не вызывается при нажатии на уведомление, вместо этого метода didFinishLaunchingWithOptions вызывается там вы должны проверить приложение погоды запускается уведомления

Помещенный ниже код в ваших didFinishLaunchingWithOptions:

var notification: UILocalNotification = (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as! UILocalNotification) 
if notification != nil { 
// handle your notification 
} 

выше код предназначен для обработки push-уведомлений, если вы воспользовались местным уведомлением, а затем попробуйте:

// if launched by the local notification 
var notification: UILocalNotification = (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification) 
if notification != nil { 

} 
+0

ok man не использовал ваш код, но ваш ответ дал мне ключ и решил мою проблему. Thanx приятель @ Сухас patil –

+0

@ Jack.Right: добро пожаловать! –

Смежные вопросы