Vinod Jadhav Vinod Jadhav - 6 months ago 13
iOS Question

how to execute some code after execution of another class method code?

I have a common web services class. in that class I have written method getcitydetail(). I want to populate that city detail after getting the result.

I have written following code in

viewDidload
:

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
let objWebService = NTMWebServices()
objWebService.getCityDetail()
}


After execution of getcitydetail, I want to do some operation here.
I think we can do it using closure in swift. but I didn't get an idea how to use it.

Answer

To use a closure in this situation try something like

func getCityDetail (completion:()->()){

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

        //background thread, do ws related stuff, the ws should block until finished here

        dispatch_async(dispatch_get_main_queue()) {
            completion() //main thread, handle completion
        }
    }
}

then you can use it like

objWebService.getCityDetail {
   //do something when the ws is complete
}