Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active February 6, 2019 08:14
Show Gist options
  • Save KentarouKanno/6512e5299b48f9ee8bba15d953288cd8 to your computer and use it in GitHub Desktop.
Save KentarouKanno/6512e5299b48f9ee8bba15d953288cd8 to your computer and use it in GitHub Desktop.
UIApplication + extension

UIApplication + extension

★ 最前面のViewControllerを取得する

extension UIApplication {
    
    // 現在の最前面のVCを取得する
    var topViewController: UIViewController? {
        guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
        
        while let presentedViewController = topViewController.presentedViewController {
            topViewController = presentedViewController
        }
        
        if let navi = topViewController as? UINavigationController {
            // NavigationControllerの場合は先頭のViewControllerを返す
            return navi.viewControllers.first
        }
        
        if let tab = topViewController as? UITabBarController {
            // TabBarControllerの場合は選択中タブのViewControllerを返す
            
            if let navi = tab.viewControllers![tab.selectedIndex] as? UINavigationController {
                // NavigationControllerの場合は先頭のViewControllerを返す
                return navi.viewControllers.first
            }
            
            return tab.viewControllers![tab.selectedIndex]
        }
        
        return topViewController
    }
}
  • openURLのバージョンを切り分けるextension
extension UIApplication {
    func openURLJudge(url: URL) {
        if UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment