0

I have the code below which needs to bring out the variable data but i dont know how to do it. Could someone please help. Thanks

class connection {
    func connection(){
        var userCheck: String = "Fail"
        let url = URL(string: "http://192.168.0.24:8080/login")!

        var request = URLRequest(url: url)

        request.httpMethod = "POST"

        let param = ["username": "admin", "password": "admin"]

        request.httpBody = try? JSONSerialization.data(withJSONObject: param, options: [])
        
        //Do not delete, testing purposes
        //print(String(data: request.httpBody!, encoding: .utf8)!)
        let session = URLSession.shared

        session.dataTask(with: request) { (data, responce, error) in
            //Do not delete, testing purposes
            //print(String(data: data!, encoding: .utf8)!)
            userCheck = String(data: data!, encoding: .utf8)!
        }.resume()
        
        //create return statement
    }
}

The above code is the class. However, i need the variable data returned from

session.dataTask(with: request) { (data, responce, error) in
                //Do not delete, testing purposes
                //print(String(data: data!, encoding: .utf8)!)
                userCheck = String(data: data!, encoding: .utf8)!
            }.resume()
            
            //create return statement

I have tried looking at how i can handle a closure statement but cant figure out how to do it in this case. would someone be willing to show me how.

James
  • 53
  • 1
  • 7
  • Use a completion handler: [How could I create a function with a completion handler in Swift?](https://stackoverflow.com/questions/30401439/how-could-i-create-a-function-with-a-completion-handler-in-swift) – pawello2222 Aug 30 '20 at 18:48
  • 2
    Possible duplicate of: [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – TylerP Aug 30 '20 at 18:51
  • Which variable do you need? userCheck? data? Please clarify. – bjrne Aug 30 '20 at 18:53
  • @bjrne data is the variable im looking for – James Aug 30 '20 at 20:06

0 Answers0