2015-12-02 78 views
2

我遇到以下問題。當我在手機上運行我的應用程序時,請觸摸圖標並選擇啓動應用程序的快速操作以呈現正確的視圖控制器,但是當我將該應用程序置於後臺並嘗試調用快速操作時,它只會打開應用程序,留下它。所以爲了使它工作,我必須每次都殺掉我的應用程序。 這裏是我的代碼:3D觸控快速操作預覽視圖控制器只有一次

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { 
    if shortcutItem.type == "com.traning.Search" { 

     let sb = UIStoryboard(name: "Main", bundle: nil) 

     let searchVC = sb.instantiateViewControllerWithIdentifier("searchVC") as! UINavigationController 

     let root = UIApplication.sharedApplication().keyWindow?.rootViewController 
     root?.presentViewController(searchVC, animated: false, completion: {() -> Void in 
      completionHandler(true) 
     }) 

    } 
} 

在此先感謝。

+1

它是否調用performActionForShortcutItem?是root = nil? – beyowulf

+0

它在哪裏調用performActionForShortcutItem? –

+1

我的意思是隻是嘗試在performActionForShortcutItem中打印某些內容以確保它被調用。也許print(root)爲什麼你可以檢查performActionForShortcutItem是否被調用,並檢查以確保root不是零。 – beyowulf

回答

4

我猜你試圖從不可見的視圖控制器呈現視圖控制器。您可以像使用擴展:

extension UIViewController { 
    func topMostViewController() -> UIViewController { 
     if self.presentedViewController == nil { 
      return self 
     } 
     if let navigation = self.presentedViewController as? UINavigationController { 
      return navigation.visibleViewController.topMostViewController() 
     } 
     if let tab = self.presentedViewController as? UITabBarController { 
      if let selectedTab = tab.selectedViewController { 
       return selectedTab.topMostViewController() 
      } 
      return tab.topMostViewController() 
     } 
     return self.presentedViewController!.topMostViewController() 
    } 
} 

extension UIApplication { 
    func topMostViewController() -> UIViewController? { 
     return self.keyWindow?.rootViewController?.topMostViewController() 
    } 
} 

你可以把這二者都在你的應用程序delegate.swift,您的應用程序委託類以上,以獲得當前可見視圖控制器。 enter image description here然後在其上顯示搜索視圖控制器。例如:

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { 
    if shortcutItem.type == "com.traning.Search" { 

     let sb = UIStoryboard(name: "Main", bundle: nil) 

     let searchVC = sb.instantiateViewControllerWithIdentifier("searchVC") as! UINavigationController 

     let topViewController = UIApplication.sharedApplication.topMostViewController() 
     topViewController.presentViewController(searchVC, animated: false, completion: {() -> Void in 
      completionHandler(true) 
     }) 

    } 
} 
+0

謝謝,但我仍然不明白該放哪個功能以及在哪裏調用它。 –

+1

對不起,我遺漏了一些東西。 – beyowulf

+0

它在此行上給出錯誤:擴展UIViewController聲明只在文件範圍 –

相關問題