I have write this class for make GET request
class GETReq{
func HTTPsendRequest(request: NSMutableURLRequest, callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
if (error != nil) {
callback("", error.localizedDescription)
} else {
callback(NSString(data: data,encoding: NSUTF8StringEncoding)!, nil)
}
}
}
task.resume()
}
func HTTPGet(url: String, callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
HTTPsendRequest(request, callback) }
}
In another class called "ManageData"
class ManageData{
func makeTheRequest()->String{
var makeReq:GETReq=GETReq();
var ret:String="";
makeReq.HTTPGet("http://www.example.com/fileExample.php") { (data:String, error:String?) -> Void in
if(error==nil){ ret="error"; } else { ret="ok"; }
}
return ret;
}
}
The problem is when in the ViewController class make
var result:String = manageData.makeTheRequest();
the "result" variable is always empty because the makeTheRequest function return the "ret" before completing the get request.
You should have
makeTheRequestadopt the same completion closure pattern you use elsewhere. So changemakeTheRequestto not return any value, but rather take acallbackparameter which is a closure that will be called when the request finishes:And you'd presumably call this like so: