Nash Porter Nash Porter - 2 months ago 16
Swift Question

Call completionHandler in function after embedded function returns value? Swift

What is the proper way to call a completionHandler() in a function that contains another function? Basically, I want to wait until the embedded function is done before calling the completionHandler.

func somefunc {

transferManager?.download(downloadRequest).continue( {(task: AWSTask) -> AnyObject! in

// Your handler code here
if (task.error != nil) {
print("- Error while downloading!")
print(task.error)
}

else if (task.result != nil) {
//let downloadOutput: AWSS3TransferManagerDownloadOutput = task.result as! AWSS3TransferManagerDownloadOutput
do {
let dFile = try NSString(contentsOf: downloadingFileURL as URL, encoding: String.Encoding.utf8.rawValue)
print(dFile)
modelsParseCSV(contentsOfURL: downloadingFileURL)
}
catch {
print("- Error: Unable to retrieve contents of csv file")
}
}
else {
print("- Uknown error: AWSS3 get file")
}


print("------------ AWS Get Models File End ----------")
return nil

})

completionHandler()
}

Answer

I was able to solve my own problem. The following code calls the completion handler and after the embedded function is complete:

func AWS_getModelsFile(AWSMake: String, completionHandler: (() -> Void)! ) {

    .........

    transferManager?.download(downloadRequest).continue( {(task: AWSTask) -> AnyObject! in

        // Your handler code here
        if (task.error != nil) {
            print("- Error while downloading!")
            print(task.error)
        }

        else if (task.result != nil) {
            //let downloadOutput: AWSS3TransferManagerDownloadOutput = task.result as! AWSS3TransferManagerDownloadOutput
            do {
                let dFile  = try NSString(contentsOf: downloadingFileURL as URL, encoding: String.Encoding.utf8.rawValue)
                print(dFile)
                modelsParseCSV(contentsOfURL: downloadingFileURL)
            }
            catch {
                print("- Error: Unable to retrieve contents of csv file")
            }
        }
        else {
            print("- Uknown error: AWSS3 get file")
        }


        print("------------ AWS Get Models File End ----------")
        completionHandler()
        return nil

    })
}