I am new on swift and trying to do something like that :
I have struct named Api Response :
struct ApiResponse {
var IsSuccess : Bool = false
var Message : String?
var ReturnedData : Data?
}
and have a func in another class named CommonHandler, that makes api call
public class CommonHandler {
public func CallApi(_ apiUrl : String , _ parameters : [String : Any] ) -> ApiResponse
{
var apiResponse = ApiResponse()
let url = URL(string: apiUrl)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
let task = URLSession.shared.dataTask(with: request , completionHandler : { data, response, error in
if let error = error {
// handle the transport error
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
// handle the server error
return
}
apiResponse.ReturnedData = data
apiResponse.IsSuccess = true
apiResponse.Message = "Succeed"
})
task.resume()
return apiResponse
}
}
I want to call this function in UIViewController like that :
var handler = CommonHandler()
let param :[String : String] = ["param":"param"]
let url = "url"
let response = handler.CallApi(url, param)
print(response.IsSuccess)
print(response.Message!)
I am aware that i can not use dataTask method like this. It's async. But how can i do api call in a non-void func and return its response data ? I parse ReturnedData json to struct then. What is the best approach in this case ? Thanks