2016-12-13 41 views
2

我使用Arduino板建立一個物聯網應用程序,並調用API來檢查Arduino板更新的引腳值。ViewDidAppear沒有執行每次應用程序來到前景

當我從API接收到更新時,我必須根據我收到的數據將我的按鈕顏色更新爲紅色或綠色。我第一次加載應用程序它工作得很好,並調用viewDidAppear()。但是,當我去背景,然後再到前景它不被稱爲。我所知道的是,每次出現視圖時都必須運行函數內部的指令,但似乎並非如此。

我試圖把我的代碼在AppDelagateapplicationDidBecomeActive(),但因爲我試圖更新我的意見和視圖不存在,但它給了我致命的錯誤發現無。 這裏是我在viewDidAppear()

override func viewDidAppear(_ animated: Bool) { 

    activityIndicator.startAnimating() 

    definingPinModes(pin: [7,6,5,4], mode: 1) 

    getAllInputValues(key: key, method: .post) { (status, newValues, msg) in 

     if status == 200 { 
      //Change button colors according to values in array 
      self.changeButtonColors(values: newValues!) 

     } else { 

      print("Error getting pin values") 

      self.alertMessage(title: "Connection Error", message: "Failed retrieving pin values") 
      return 
     } 
     self.activityIndicator.stopAnimating() 
    } 

} 

回答

2

除了viewDidAppear指令,你可以有你的視圖控制器觀察UIApplicationDidBecomeActive

private var observer: NSObjectProtocol? 

override func viewDidLoad() { 
    super.viewDidLoad() 

    observer = NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: .main) { [weak self] notification in 
     self?.updateUI() 
    } 
} 

deinit { 
    if let observer = observer { 
     NotificationCenter.default.removeObserver(observer) 
    } 
} 

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    updateUI() 
} 

private func updateUI() { 
    // do your UI update stuff here 
} 
+0

感謝搶第一時間使用這些觀察員。但是我有一個關於創建NotificationCenter本身的實例的問題。我沒有創建實例並需要調用deinit。爲什麼你的方式比直接使用NotificationCenter類更好? –

+0

我沒有創建'NotificationCenter'實例。我只使用'default'單身人士。我所做的只是添加一個觀察者到該通知中心並保存對該觀察者(而不是中心)的引用,以便我可以在'deinit'中刪除該觀察者。就您爲什麼這麼做而言,從歷史上看,當一個對象被釋放時,通知中心停止發送通知是至關重要的。現在也許這是一個不會被釋放的根視圖控制器,但它是一個很好的實踐,可以自行清理,以便代碼可以在任何上下文中使用。 – Rob

+0

請參閱['addObserver(forName:object:queue:using:)'](https://developer.apple.com/reference/foundation/notificationcenter/1411723-addobserver)文檔,瞭解添加觀察者並刪除它們的示例。 – Rob

相關問題