2017-08-24 61 views
0

我在產生警報視圖時出現此錯誤「嘗試在其視圖不在窗口層次中呈現!」。 請看下面我的代碼。我正在使用操作隊列來執行警報任務。UIAlertController在生成alertview時給出錯誤

class AlertOperation: ASOperation { 
    // MARK: Properties 

    fileprivate let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert) 
    fileprivate let presentationContext: UIViewController? 

    var title: String? { 
     get { 
      return alertController.title 
     } 

     set { 
      alertController.title = newValue 
      name = newValue 
     } 
    } 

    var message: String? { 
     get { 
      return alertController.message 
     } 

     set { 
      alertController.message = newValue 
     } 
    }  

    // MARK: Initialization 
    init(presentationContext: UIViewController? = nil) { 
     self.presentationContext = presentationContext ?? UIApplication.shared.keyWindow?.rootViewController 

     super.init() 

     addCondition(AlertPresentation()) 
     /* 
      This operation modifies the view controller hierarchy. 
      Doing this while other such operations are executing can lead to 
      inconsistencies in UIKit. So, let's make them mutally exclusive. 
     */ 
     addCondition(MutuallyExclusive<UIViewController>()) 
    } 

    func addAction(_ title: String, style: UIAlertActionStyle = .default, handler: @escaping (AlertOperation) -> Void = { _ in }) { 
     let action = UIAlertAction(title: title, style: style) { [weak self] _ in 
      if let strongSelf = self { 
       handler(strongSelf) 
      } 
      self?.finish() 
     } 

     alertController.addAction(action) 
    } 

    override func execute() { 
     guard let presentationContext = presentationContext else { 
      finish() 
      return 
     } 

     DispatchQueue.main.async { 
      if self.alertController.actions.isEmpty { 
       self.addAction("OK") 
      } 
      presentationContext.present(self.alertController, animated: true, completion: nil) 
     } 
    } 
} 

它第一次工作正常,但如果我按下取消按鈕上的警報比它給我上面的錯誤。目前,如果用戶按取消按鈕,我將從同一功能打開另一個警報。

final func finish(_ errors: [NSError] = []) { 
    if !hasFinishedAlready { 
     hasFinishedAlready = true 
     state = .finishing 

     let combinedErrors = _internalErrors + errors 
     finished(combinedErrors) 

     for observer in observers { 
      observer.operationDidFinish(self, errors: combinedErrors) 
     } 

     state = .finished 
    } 
} 
+0

你爲什麼需要手術?你也可以格式化你的代碼嗎?謝謝。 –

+0

格式?,你的意思 –

+0

我會爲你做。但下一次,請自己動手。 –

回答

0

檢查是否存在一些問題與您presentationContext,也就是說,如果它認爲是存在於窗口層次,

對於這種嘗試用

UIApplication.shared.keyWindow?.rootViewController?.present(self.alertController, animated: true, completion: nil) 
更換

presentationContext.present(self.alertController, animated: true, completion: nil) 

如果它適用於window'srootViewController,然後嘗試解決您的presentationContext

+0

這應該是一個評論,而不是一個響應。它不提供任何附加價值。 –

+0

它不適合我 –