Kahsn Kahsn - 3 months ago 38
Swift Question

Calling viewdidload and viewdidappear again

My app is a geolocation based app. I've implemented to pop up a UIAlertview as soon as some users press "Don't allow location service" button to guide them to settings again to turn on the service.

The problem I'm facing is that when user finally turns on the button, the data are not being loaded to the tableview since my data calling functions are in

viewdidload
and
viewdidappear
. Is there a way to call those functions again?

I did something like below and it totally crashes my app:

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
}


When I was doing this way, it was kept calling viewdidload like million times before it crashed the app. Any advices are appreciated

Answer

Simply move your data calling functions outside of viewDidLoad and viewDidAppear:

Instead of

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

write

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

func doSomeStuff() {
    // do some stuff
}

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