0

I'm still somewhat new to Swift. But I want to implement an HTTP request with Swift. My problem here is that I can't return the return value because the function is running asynchronously. Therefore, only the output via print() works. I've already tried to add async and await. however, don't get any further.

Here my code:

import SwiftUI

func HTTPRequest(parameter: String, app_url: String) -> String{
    let session = URLSession(configuration: .default)
    let url = URL(string: "http:10.203.24.212/"+app_url)!
    var request = URLRequest(url: url)
    var return_value = ""
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpBody = parameter.data(using: .utf8)
    let task = session.dataTask(with: request) { data, response, error in
        if let data = data {
            return_value = (String(data: data, encoding: .utf8)!)
            print(return_value)
        }
    }
    task.resume()
    return return_value
}

1 Answers1

0

You have to use completion handler instead return.

func HTTPRequest(parameter: String, app_url: String, userCompletionHandler: @escaping (String?){
    let session = URLSession(configuration: .default)
    let url = URL(string: "http:10.203.24.212/"+app_url)!
    var request = URLRequest(url: url)
    var return_value = ""
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpBody = parameter.data(using: .utf8)
    let task = session.dataTask(with: request) { data, response, error in
        if let data = data {
            return_value = (String(data: data, encoding: .utf8)!)
            print(return_value)
            
            userCompletionHandler(return_value)
        }
    }
    task.resume()

}

and to use it :

HTTPRequest(parameter: "xxx", app_url: "xxx", userCompletionHandler: { returnReponse in
                                

    let data = returnReponse

    ...
                            
                            
})
dibs
  • 174
  • 1
  • 12