簡體   English   中英

在AppDelegate中使用推送通知重定向視圖

[英]Redirect a View with Push Notification in AppDelegate

我的目標是編寫一個代碼,當用戶獲得推送通知時,我希望將該用戶重定向到另一個視圖。 如果用戶帶有推送通知,並且他是第一次查看控制器(歡迎主屏幕等(但未登錄))

var rootViewController = self.window!.rootViewController as! ViewController
rootViewController.performSegueWithIdentifier("hospitalSegue", sender: self)

這幾行代碼正在工作,但是,如果用戶已經在另一個視圖控制器(登錄/登錄/用戶頁面等),這段代碼不起作用和重定向。 我嘗試了一切,但仍然無法提出解決方案。 我的最終目標是:

if let rootViewController = self.window!.rootViewController as? ViewController
{
    var rootView: UserViewController = UserViewController()

    if let window = self.window{
        window.rootViewController = rootView
    }

    rootViewController.performSegueWithIdentifier("hospitalSegue", sender: self)
    println(self.window?.rootViewController)
}

誰能給我一個想法?

答案代碼是Objective-C,我想談談邏輯。 要執行此操作,在創建推送通知時,必須設置userInfo值以使用推送通知傳遞數據。

使用此委托方法: application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

您可以通過處理userInfo來決定要顯示哪個視圖

NSDictionary *segueDictionary = [userInfo valueForKey:@"aps"];

NSString *segueName=[[NSString alloc]initWithFormat:@"%@",[segueDictionary valueForKey:@"segueName"]];

if([segueName isEqualToString:@"hospitalSegue"]) 
{
// implement your code to redirect
}

答案代碼是Objective-C,你可以使用下面的方法從app delegate prentviewcontroller我使用下面的代碼解決了這個問題:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
      [[self topViewController]presentViewController:nav animated:YES    completion:nil];
}

- (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM