I have a program that processes input, one record at a time. For each record it does an HTTP POST to look up some information (based on the contents of that record) and it wants to append at the end of the record some of the information it received in the response.
For my purposes, the process of getting the input record, doing the HTTP POST, and appending the response to the record is an atomic operation. In Cocoa, NSURLSession is asynchronous. I'm unsure how to wait for the response and append it to the current record before going on to the next record.
Here is my (non-working) code. The problem is at the end where I don't want to execute "record.append(results)" until the closure has completed and produced "results". There is the closely related problem that "results" is defined in the closure and is not in scope outside of it. How can I get the behavior I want? (I'd prefer seeing code in Swift, but if you know how to do this in Objective-C, please show me and I'll try to translate it.)
I'd also like to be able to pass some additional information (that changes with each pass through the "for in" loop) to the closure for it to use in the analysis of the response.
I'd also like to know how to get multiple output parameters from the closure. I thought that perhaps I could have an output structure, so that it would be one parameter, but would hold the various pieces of information that I want. I suppose that if that isn't possible, I could just pack what I am thinking of as multiple output parameters into a string that would count as a single output parameter.
let regex0: NSRegularExpression = NSRegularExpression(pattern: "\\A.*Part1:(.*?)<.*Part2:(.*?)<.*Part 3:(.*?)<.*\\z", options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)!
let wdivURL = NSURL(string: "http://NotTheRealDomain.com")
let request = NSMutableURLRequest(URL:wdivURL!)
request.HTTPMethod = "POST"
var myArray: [String] = ["First", "Second", "Third"]
for record in myArray {
var bodyData: String = "Not the real body" + record
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {data, response, error in
if error != nil {
println("NSURLSession error = \(error)")
return
}
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
var results: String = regex0.stringByReplacingMatchesInString(responseString as String, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, responseString.length), withTemplate: "\t$1\t$2\t$3")
}
task.resume()
record.append(results)
}