Search code examples
swiftnsurlconnectionnsurlsessionsynchronous

Swift wait until dataTaskWithRequest has finished to call the return


I am new to Swift and I have a question regarding synchronous calls. I would like to make a synchronous call to dataTaskWithRequest, so that the return method is called once the dataTaskWithRequest is finished. Here is my code:

private func sendRequest (request: NSURLRequest) -> NSData{
    let session = NSURLSession.sharedSession()
    var dataReceived: NSData = NSData ()
    let task = session.dataTaskWithRequest(request) { data, response, error in
        if error != nil{
            print("Error -> \(error)")
            return
        }
    dataReceived = data!
    }
    task.resume()
    return dataReceived
}

What is the best way to do it? I have tried with a completion handler but I am not able to do it.

Thank you very much in advance for the help.


Solution

  • completion is the right and the best way in swift!

      func sendRequest (request: NSURLRequest,completion:(NSData?)->()){
    
        NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            if error != nil{
                return completion(data)
            }else{
                return completion(nil)
            }
        }.resume()
    }
    

    and call:

      sendRequest( yourRequest ) { data in
            if let data = data {
                 // do something
            }
       }}