uialertview - Get the top ViewController in iOS Swift -


i want implement separate errorhandler class, displays error messages on events. behavior of class should called different other classes. when error occurs, have uialertview output. display of alertview should on top. no matter error gets thrown, topmost viewcontroller should display alertmessage (e.g. when asynchronous background process fails, want error message, no matter view displayed in foreground).

i have found several gists seem solve problem (see code below). calling uiapplication.sharedapplication().keywindow?.visibleviewcontroller() return nil-value.

extension gist

extension uiwindow { func visibleviewcontroller() -> uiviewcontroller? { if let rootviewcontroller: uiviewcontroller  = self.rootviewcontroller {   return uiwindow.getvisibleviewcontrollerfrom(rootviewcontroller) } return nil }  class func getvisibleviewcontrollerfrom(vc:uiviewcontroller) -> uiviewcontroller {  if vc.iskindofclass(uinavigationcontroller.self) {    let navigationcontroller = vc as! uinavigationcontroller   return uiwindow.getvisibleviewcontrollerfrom( navigationcontroller.visibleviewcontroller)  } else if vc.iskindofclass(uitabbarcontroller.self) {    let tabbarcontroller = vc as! uitabbarcontroller   return uiwindow.getvisibleviewcontrollerfrom(tabbarcontroller.selectedviewcontroller!)  } else {    if let presentedviewcontroller = vc.presentedviewcontroller {      return uiwindow.getvisibleviewcontrollerfrom(presentedviewcontroller.presentedviewcontroller!)    } else {      return vc;   } } } } 

amit89 brought way solution up. have call .windowproperty of appdelegate. changed swift code link below work intended find topmost viewcontroller. make sure, view in view hierarchy. method cannot called .viewdidload

extension find topmost viewcontroller*

extension uiapplication {   class func topviewcontroller(base: uiviewcontroller? = (uiapplication.sharedapplication().delegate as! appdelegate).window?.rootviewcontroller) -> uiviewcontroller? {     if let nav = base as? uinavigationcontroller {       return topviewcontroller(base: nav.visibleviewcontroller)     }     if let tab = base as? uitabbarcontroller {       if let selected = tab.selectedviewcontroller {         return topviewcontroller(base: selected)       }     }     if let presented = base?.presentedviewcontroller {       return topviewcontroller(base: presented)     }     return base   } } 

this code originated github user yonat in comment objectivec equivalent. changed bits of code work without .keywindow property


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -