Swift尝试显示其视图不在窗口层次结构中的UIAlertController(在TWTRShareEmailViewController之后显示)

Mar*_* Dm 14 email twitter ios swift uialertcontroller

我在我的应用程序的注册过程中使用Twitter登录.而且我要求用户的电子邮件.一旦我得到它,我想呈现一个UIAlertController.

这是我的代码:

func askForTWMail(){
    if (Twitter.sharedInstance().session() != nil) {
        let shareMailVC=TWTRShareEmailViewController(completion: {(mail:String!, error:NSError!) in
            if (mail != nil) {
                print("GOT MAIL: \(mail)")
                self.gotMail()
            }else{
                print("MAIL VC ERROR: \(error)")
            }
        })
        println("PRESENT MAIL VC")
        self.presentViewController(shareMailVC, animated: true, completion: nil)
    }else{
        println("User not logged in")
    }
}

func gotMail(){
    var alertController=UIAlertController(title: "Some title", message: "Some message", preferredStyle: UIAlertControllerStyle.Alert)
    var okAction=UIAlertAction(title:"Yes", style: UIAlertActionStyle.Default) {
    UIAlertAction in
    //some action
    }
    var cancelAction=UIAlertAction(title:"No", style: UIAlertActionStyle.Cancel){
    UIAlertAction in
    //some action
    }
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)
    self.presentViewController(alertController, animated: true, completion: nil)                
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误(我猜因为TWTRShareEmailViewController没有被解雇):

警告:尝试在视图不在窗口层次结构中的xViewController上显示UIALertController!

知道怎么写这个吗?我怎么知道何时TWTRShareEmailViewController被解雇以继续注册过程并能够展示我的UIAlertController?我不知道与之相关的委托方法TWTRShareEmailViewController.

任何帮助表示赞赏.谢谢.

Mar*_* Dm 31

在这里找到解决方案.我可能做错了,但如果不是,它可能是一个Apple bug.解决方法是延迟以下内容的呈现UIAlertController:

dispatch_async(dispatch_get_main_queue(), ^{
    self.presentViewController(alertController, animated: true, completion: nil)
})
Run Code Online (Sandbox Code Playgroud)

编辑:我发现了另一种解决方法(我不再使用我在这里放下的解决方案).我不得不改变这一点,因为Twitter登录也破坏了我在VC之间的转换.

我现在调用一个特定的UIViewController(我称之为类似的东西TWLoginVC),我在那里做所有的Twitter登录和其他东西.视图只是黑色,因此用户看不到该过程实际上是在另一个VC中完成的(他只需要拿起他想要登录的Twitter用户).我想你也可以把一个明确的背景变得更加隐形.

当我调用此视图控制器并将其关闭时,转换不会应用于它,我没有任何问题.


编辑 Swift的更新:

DispatchQueue.main.async{
     self.present(alertController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)


Asd*_*bal 5

这是基于Marie Dm的答案,在Xcode 8上测试的Swift 3的更新答案.

DispatchQueue.main.sync {
     self.present(alertController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)