再次调用 viewdidload 和 viewdidappear

Calling viewdidload and viewdidappear again

我的应用程序是基于地理位置的应用程序。我已经实现了在某些用户按下 "Don't allow location service" 按钮后立即弹出 UIAlertview 以引导他们再次进行设置以打开服务。

我面临的问题是,当用户最终打开按钮时,由于我的数据调用函数在 viewdidloadviewdidappear 中,所以数据没有加载到表视图中。有没有办法再次调用这些函数?

我做了类似下面的事情,它完全崩溃了我的应用程序:

extension ExploreViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

    switch status {
    case .Denied:
        // Changed status to denied
        self.locationAlert = UIAlertView(title: "Location Services Permission Needed", message: "Location service needs to be turned on to use Peek! Please press setting button below and turn the service on!", delegate: self, cancelButtonTitle: "Settings")
        locationAlert.show()
        break
    case .AuthorizedWhenInUse:
        self.viewDidLoad()
        self.viewDidAppear(true)
        break
    default
        break
}

当我这样做时,它一直在调用 viewdidload 数百万次,然后才使应用程序崩溃。任何建议表示赞赏

Never never never never 调用 viewDidLoadviewDidAppear(除了在后一种情况下调用 super)。它们是运行时发送给您的消息,用于报告视图控制器生命周期中的各个阶段。

func myCodeToRun() {
    //put all the code you want to run here
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    myCodeToRun()
}

extension ExploreViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

switch status {
case .Denied:
    // Changed status to denied
    self.locationAlert = UIAlertView(title: "Location Services Permission Needed", message: "Location service needs to be turned on to use Peek! Please press setting button below and turn the service on!", delegate: self, cancelButtonTitle: "Settings")
    locationAlert.show()
    break
case .AuthorizedWhenInUse:
    myCodeToRun()
    break
default
    break

}

只需将您的数据调用函数移到viewDidLoadviewDidAppear之外:

而不是

override func viewDidLoad() {
    // do some stuff
}

override func viewDidLoad() {
    super.viewDidLoad()
    doSomeStuff()
}

func doSomeStuff() {
    // do some stuff
}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    // do your current logic
    doSomeStuff()
}