2016-06-19 87 views
0

我剛接觸swift iOS編程。我寫了一些代碼。很簡單,我想執行一個警報,然後通過「performSegueWithIdentifier」移動到另一個視圖控制器。但我得到這樣的輸出:嘗試在ViewController上呈現UIViewController,它已經呈現UIAlertController

「警告:試圖提出的UIViewController:0x7fa05b72dd60上Kilaundry.ViewController:0x7fa05b49a2c0這已經是呈現UIAlertController:0x7fa05d859d70」

我想警告這個代碼後:「NSOperationQueue .mainQueue()。addOperationWithBlock」。

爲什麼我不能執行警報,然後通過「performSegueWithIdentifier」移動到另一個視圖控制器?請幫我找出爲什麼會發生這種警告。

這是我的代碼:

     if let data = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary { 
          print(jsonResult) 

          Resp_code = jsonResult["Resp_code"] as? String; 
          Resp_message = jsonResult["Resp_message"] as? String; 

          if Resp_code == "01" { 
           NSOperationQueue.mainQueue().addOperationWithBlock { 
            let alert = UIAlertController(title: "Information", message:Resp_message!, preferredStyle: .Alert) 
            alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in }) 
            self.presentViewController(alert, animated: true){} 
            self.performSegueWithIdentifier("LoginSucceed", sender: self) 
           } 
          } else { 

           NSOperationQueue.mainQueue().addOperationWithBlock { 
           let alert = UIAlertController(title: "Oops!", message:"It seems "+Resp_message!, preferredStyle: .Alert) 
           alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in }) 
           self.presentViewController(alert, animated: true){} 
           } 
          } 
         } 
+0

你爲什麼使用NSOperation隊列?如果你想在主線程中使用它,我想你想使用dipatch_get_main_queue()。 :/ – Dershowitz123

回答

3

您收到此錯誤,因爲你正試圖呈現目前已顯現出模態VC視圖控制器上的模態視圖控制器 - 你提出了一個報警控制器,然後立即觸發一個segue(這也可能是一種模式)。 視圖控制器在給定時間只能有一個呈現視圖控制器。做你想做什麼的最簡單的方法是在「LoginSucceeded」segue呈現的VC上呈現'OK'警報。

但是,我會重新考慮是否應該顯示警報。我建議你閱讀official Apple guidelines on the use of alerts - 基本上說'除非你真的需要'不要顯示警報'。特別是,不要顯示警報通知用戶應用程序正常運行。 當您的請求失敗時顯示錯誤警報是正確的 - 當用戶成功登錄時顯示一個不是必需的。

相關問題