functionswiftcompletionhandler

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


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


Solution

  • 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
        }
    })