2016-11-19 56 views
0

我有一個更新函數,當我的應用程序中的刷新按鈕被按下時調用。 在更新函數中,我調用一些其他函數來獲取新數據,然後使用新值設置所有文本字段。只要該函數沒有完全執行,我想顯示一個UIAlertController,它向用戶顯示一個Alert Popup。 爲UIAlertController的代碼如下所示:只要函數持續顯示UIAlertController

@IBAction func btnReloadDataTapped(_ sender: AnyObject) { 
    let refreshAlert = UIAlertController(title: "Refreshing Data", message: "This might take a few moments.", preferredStyle: UIAlertControllerStyle.alert) 

    present(refreshAlert, animated: true, completion: nil) 
} 

是否有與斯威夫特3執行此任務,乾淨的方式?

回答

1

當所有的任務都完成,在UIViewController只是叫

self.dismiss(animated: true, completion: nil) 
0

我使用NotificationCenter類走近類似的情景。你也可以用回調或委託來解決這個問題。

我只會在下面討論NotificationCenter和回調方法,因爲我認爲委託模式在這裏不太合適。

這裏是通知的方法可能是什麼樣子:

  1. 在類/結構,負責獲取新的數據,你要創建一個使用通知中心的post方法的通知。

喜歡的東西:

func fetchData() { 
    // Code that fetches the new data... 

    // Create the notification 
    NotificationCenter.default.post(name: "NewDataReceived", object: self) 
} 
  • 然後在有你希望你的控制器啓動時增加一個觀察者的重載按​​鈕UIViewController
  • 是這樣的:

    required init?(coder aDecoder: NSCoder) { 
        super.init(coder: aDecoder) 
    
        // Create the observer 
        NotificationCenter.default.addObserver(self, #selector(dismissAlertView), name: "NewDataReceived", object: nil) 
    } 
    
  • 當通知被張貼的獲取數據的操作,然後您UIViewController將被通知,並且您中指示的方法你的觀察者將被調用。

  • 這是在這種方法,你可以然後解僱UIAlertController

  • 喜歡的東西:

    // Also in your UIViewController... 
    func dismissAlertView() { 
        refreshAlert.dismiss(animated: true, completion: nil) 
    } 
    

    這就要求你UIAlertController是你的UIViewController的實例屬性。

    上面的代碼只是爲了說明你可以採取的方法。我建議參考NotificationCenter的文檔。

    https://developer.apple.com/reference/foundation/nsnotificationcenter

    這裏是回調的方法可能是什麼樣子:

    1. 變化負責獲取數據採取的函數方法的簽名。

    是這樣的:

    func fetchData(completionHandler:() -> Void) { 
        // Code that fetches the new data... 
    
        // Call the completion handler 
        completionHandler() 
    } 
    
  • 處理回調在UIViewController
  • 是這樣的:

    @IBAction func btnReloadDataTapped(_ sender: AnyObject) { 
        let refreshAlert = UIAlertController(title: "Refreshing Data", message: "This might take a few moments.", preferredStyle: UIAlertControllerStyle.alert) 
    
        present(refreshAlert, animated: true, completion: nil) 
    
        // Fetch your new data... 
        someInstance.fetchData() { 
    
         // Handle the callback of the fetch data call 
         DispatchQueue.main.async { 
          refreshAlert.dismiss(animated: true, completion: nil) 
         } 
        } 
    } 
    

    同樣,這僅用於說明目的。您可以在此處瞭解有關回調的更多信息:https://www.andrewcbancroft.com/2016/02/15/fundamentals-of-callbacks-for-swift-developers/