Hi,
I'm using Swift 2 and need to do 2 two HTTP Post requests. In the first, I need to write some command to an REST server and if the result be successfull, do another request for reading some data from it. In order to perform it I've developed the funtios below:
public func commandWrite(tag:String, value:Int16, completionHandler:(Bool, String)-> Void) {
var url = NSURL(string: (urlBase as String) + "write")!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var error : NSErrorPointer = NSErrorPointer()
var dictData: NSMutableDictionary = NSMutableDictionary()
dictData.setValue(tag, forKey: "id")
dictData.setValue(String(value), forKey: "v")
let postData = NSJSONSerialization.dataWithJSONObject([dictData], options: NSJSONWritingOptions(0), error: error)
request.HTTPBody = postData as NSData!
var response : NSURLResponse = NSURLResponse()
var session = NSURLSession.sharedSession()
var jsonData: NSDictionary = NSDictionary()
var task = session.dataTaskWithRequest(request){ data, response, error -> Void in
if(response) != nil{
if(data) != nil{
jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonData)
if(jsonData.count > 0){
let usefullData = jsonData.valueForKey("writeResults") as! NSArray
let success = usefullData[0].valueForKey("s") as! Bool
var errorMsg = ""
if success == false{
error = dados[0].valueForKey("r") as! String
}
completionHandler(success,errorMsg)
}
else{
completionHandler(false,"Without server connection.")
}
}
else{
completionHandler(false,"Without server connection.")
}
}
else{
completionHandler(false,"Without server connection.")
}
}
task.resume()
}
public func tagRead(tag:String, completionHandler:(Bool, String, Double)-> Void){
var url = NSURL(string: (urlBase as String) + "read")!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var error : NSErrorPointer = NSErrorPointer()
let postData = NSJSONSerialization.dataWithJSONObject([tag], options: NSJSONWritingOptions(0), error: error)
request.HTTPBody = postData as NSData!
var response : NSURLResponse = NSURLResponse()
var session = NSURLSession.sharedSession()
var jsonData: NSDictionary = NSDictionary()
var task = session.dataTaskWithRequest(request) { data, response, error -> Void in
if(response) != nil{
if(data) != nil{
jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonData)
if(jsonData.count > 0){
let usefullData = jsonData.valueForKey("readResults") as! NSArray
let success = usefullData[0].valueForKey("s") as! Bool
var value = 0.0
var errorMsg = ""
if success{
value = data[0].valueForKey("v") as! Double
} else{
errorMsg = data[0].valueForKey("r") as! String
}
completionHandler(success,errorMsg, value)
}
completionHandler(false,"Without server connection.", 0.0)
}
}
else{
completionHandler(false,"Without server connection.", 0.0)
}
}
else{
completionHandler(false,"Without server connection.", 0.0)
}
}
task.resume()
}
I've read that for use such assync calls its necessary to use between "{" and "}", so I tried to do something like:
func getData(){
let tag = tagBase + (selEqp as String) + "." + textFieldBlocoMedidor.text
var sucEsc:Bool = false
var erroLiga:String = ""
var estado:Double = 0
writeCommand((tag + "_CMD1"), valor: 4){ sucWrite, errorWrite in
ProgressVale.shared.showOverlay(self.view)
if (sucWrite){
var sucLeit: Bool
var erroLeit:String
readTag(tag + "_EST1"){ sucRead, errorRead, value in
ProgressVale.shared.hideOverlayView()
if (sucRead){
self.textFieldData.text = String(format: "%.1f", value as Double)
let alert = UIAlertView()
alert.title = "Warning!"
alert.message = "Data read is: \(value)"
alert.addButtonWithTitle("OK")
alert.show()
}else{
let alert = UIAlertView()
alert.title = "Warning!"
alert.message = errorRead
alert.addButtonWithTitle("OK")
alert.show()
}
}
}else{
ProgressVale.shared.hideOverlayView()
let alert = UIAlertView()
alert.title = "Warning!"
alert.message = errorWrite
alert.addButtonWithTitle("OK")
alert.show()
}
}
}
The getData funcion works fine, I can see on println's debugger that the writeCommand and readTag sequence happens correctly and fast as expected. But it seems there is some delay to show alert views, in case of successfull or error and, in case of sucess, self.textFiledData.text is completed only few seconds (10~30) after readTag's completion handler have been executed. Could anyone help me?
Regards