jjx
jjx

Reputation: 257

Make Asynchronous GET/POST request in Swift

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.

Upvotes: 1

Views: 2154

Answers (1)

Rob
Rob

Reputation: 437582

You should have makeTheRequest adopt the same completion closure pattern you use elsewhere. So change makeTheRequest to not return any value, but rather take a callback parameter which is a closure that will be called when the request finishes:

func makeTheRequest(callback: (String, String?) -> Void) {
    var makeReq:GETReq=GETReq();
    var ret:String="";

    makeReq.HTTPGet("http://www.example.com/fileExample.php", callback)
}

And you'd presumably call this like so:

makeTheRequest() { string, error in 
    if error != nil {
        println(error)
        return
    }

    // if you got here, you can use `string`

    println(string)
}

Upvotes: 5

Related Questions