简体   繁体   中英

Swift: How to call functions where one of the arguments is a completionHandler

I'm very new to XCode and Swift and in my iOS app I've written a method to perform a POST request to a php file on a server by following some answers here in stackoverflow:

func closeTaskService(id_task:Int, completionHandler: (response: NSString) -> ()) {

    let request = NSMutableURLRequest(URL: NSURL(string: Settings.webServerGetUserTasks)!)
    request.HTTPMethod = "POST"
    let postParams = "action=close&id_task=\(id_task)"
    request.HTTPBody = postParams.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        println("response = \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString!)")

        completionHandler(response: responseString!)

    }
    task.resume()
}

where

webServerGetUserTasks = "http://localhost:8888/excogitoweb/mobile/handleTasks.php"

The problem is that I have no idea how how to call that function on my view controller class. The examples I have seen don't have a parameter in the function so, when it is called, they simply write the closure. Here's what I have tried up to now:

self.taskService.closeTaskService(self.taskCollection[indexPath.row].id), {(response: NSString) -> () in
        println("response = \(response)")})

but XCode shows many error and it suggests me to add the ';' in two or three places...would you please explain me how to call this kind of functions and how to write the closure?

Was a simple misspelling I guess. When I call functions with completion handlers I always let auto complete do it's job and then double click on the things that have a rounded box around them. This always gives the correct syntax.

self.taskService.closeTaskService(self.taskCollection[indexPath.row].id) { (response) -> () in
    print(response)
}

Try this

func closeTaskService(id_task:Int, completionHandler: (response: NSString) -> ()) {
    let request = NSMutableURLRequest(URL: NSURL(string: "http://myserverip/myfile.php")!)
    request.HTTPMethod = "POST"
    let postParams = "action=close&id_task=\(id_task)"
    request.HTTPBody = postParams.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        println("response = \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString!)")
        completionHandler(response: responseString!)
    }
    task.resume()
}

and call your method like this

self.closeTaskService(12, completionHandler: { (response) -> () in
    //handle response
})

Try this

self.taskService.closeTaskService(self.taskCollection[indexPath.row].id), completionHandler: {(response: NSString) -> () in
            println("response = \(response)")
})

The first thing you need to understand is how is defined the Closure Expression Syntax , according to Apple closure expression syntax has the following general form:

{ (parameters) -> return type in
    statements
}

According to Apple :

If you need to pass a closure expression to a function as the function's final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
}

// here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure({
    // closure's body goes here
})

// here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
}

Then, I think with the answers above and this asnwer you can understand better how closures work and how call it. Nevertheless, I strongly recommend you read the Closures chapter of the Apple book to understand in depth how it works.

I hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM