Shohrab Shohrab - 7 months ago 22
Swift Question

Swift 2 Call Function in CompletionHandler

I am new in Swift. I am unable to call a function as soon as I download JSON data from server using

NSURLSession
. Here is my code -

func loadTableViewWithServerData(_url:String){
showOverLayView()
let postEndpoint: String = _url
let session = NSURLSession.sharedSession()
let url = NSURL(string: postEndpoint)!
session.dataTaskWithURL(url, completionHandler: {
(data, response, error) in

guard let responseData = data else {
print("Error: did not receive data")
return
}
let post: NSMutableArray
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSMutableArray
self.dataArray = SHDataAccess().arrayFromPlist(post)

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.questionTableView.reloadData()

//hideOverLayView() /* it shows error here*/

})


} catch {
print("error trying to convert data to JSON")
}

}).resume()
}


When I try to call
hideOverLayView() /* it shows error here*/
it shows the error:


Error : Call to method 'hideOverLayView()' in closure requires explicit 'self' to make capture semantics explicit.


How do I fix this? Or what is the right way to call another function where i refresh my view when server data is available.

Here is my
hideOverLayView() /* it shows error here*/
function -

func hideOverLayView(){
self.overLayView.imageProgress.stopAnimating()
UIView.animateWithDuration(0.5, animations: {
self.overLayView.hidden = true
})
}

JAL JAL
Answer

When you're in a closure, you need to explicitly call class methods with self. Without self, the context of your method is ambiguous.

Change hideOverLayView() to self.hideOverLayView() inside your dispatch_async block.