Shohrab Shohrab - 1 year ago 69
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

. Here is my code -

func loadTableViewWithServerData(_url:String){
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")
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

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


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


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(){
UIView.animateWithDuration(0.5, animations: {
self.overLayView.hidden = true

Answer Source

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.