How could I create a function with a completion handler in Swift?

traw1233 picture traw1233 · May 22, 2015 · Viewed 117.8k times · Source

I was just curious as to how I would approach this. If I had a function, and I wanted something to happen when it was fully executed, how would I add this into the function? Thanks

Answer

tounaobun picture tounaobun · May 22, 2015

Say you have a download function to download a file from network, and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})

Hope it helps.