我的应用从服务器下载更新.为此,它将设备上的数据与服务器上可用的数据进行比较.如果存在不匹配,则将布尔值“updateAvailable”设置为true,并向用户显示交互式UILabel,指示他们可以下载
(略微简化的代码)
class ViewController: UIViewController { @IBOutlet weak var updateLabel: UILabel! func updateChecker(){ let deviceVersion = self.settingsController.getDeviceVersion() //Get Server Version (Async) _ = settingsController.getServerVersion() { (data) -> () in dispatch_async(dispatch_get_main_queue()){ if deviceVersion != data{ self.updateAvailable = true } else{ self.updateAvailable = false } //Update UI self.updateUI() } } } func updateUI(){ if updateAvailable{ updateLabel.text = "Update Available" } else{ updateLabel.text = "App Up To Date" } }
在触摸此更新标签时,应用程序会触发“updateViewController”的自定义segue:
@IBAction func getUpdateLabelPressed(sender: UITapGestureRecognizer) { if updateAvailable{ self.performSegueWithIdentifier("segueToUpdateView", sender: self) }
UpdateViewController从服务器下载数据(异步),然后被解除:
class UpdateViewController: UIViewController{ override func viewDidLoad() { super.viewDidLoad() //Create Settings Controller + Get Update let sc = SettingsController() sc.getUpdate({ (success) -> () in if success{ dispatch_async(dispatch_get_main_queue()){ print("Update Success") self.dismissViewControllerAnimated(true, completion: nil) } } else{ dispatch_async(dispatch_get_main_queue()){ print("Update Failed") self.dismissViewControllerAnimated(true, completion: nil) } } }) }
在解除UpdateViewController时,会显示主ViewController,但“updateAvailable”仍设置为true,并且updateLabel仍处于活动状态.
触发另一个自定义Segue回ViewController / Root ViewController对我来说不是一个选项,因为它通过在Stack中创建多个’ViewController’实例来破坏后台更新提取.
onViewDidAppear()在这种情况下也是不合适的,因为它会导致繁重的网络/服务器流量.
如何解除UpdateViewController并重新加载以前的ViewController或发送回触发ViewController的updateChecker()方法的数据?或者清除整个ViewControllerStack并重启应用程序?
我理解代理安排似乎是合适的,但是之前关于这个主题的SO问题和答案如this one是针对Objective-C的,我无法为Swift 2.0调整这些答案.
任何帮助将不胜感激.
在UpdateViewController中创建一个闭包属性clearUpdateAvailable:class UpdateViewController: UIViewController { var clearUpdateAvailable: (()->())? override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) clearUpdateAvailable?() } }
您可以在viewWillDisappear中或从服务器接收数据的方法中调用clearUpdateAvailable.
在ViewController中,在按ID显示UpdateViewController时提供闭包.
let storyboard = UIStoryboard(name: "Main", bundle: nil) if let updateViewController = storyboard.instantiateViewControllerWithIdentifier("updateViewController") as? UpdateViewController { updateViewController.clearUpdateAvailable = { [weak self] in self?.updateAvailable = false self?.updateUI() } presentViewController(updateViewController, animated: true, completion: nil) }