我是swift的新手,并尝试做类似的事情:
我有一个名为Api Response的结构:
struct ApiResponse {
var IsSuccess : Bool = false
var Message : String?
var ReturnedData : Data?
}
并在名为CommonHandler的另一个类中有一个func,它使api调用
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
}
}
我想在UIViewController中调用这个函数:
var handler = CommonHandler()
let param :[String : String] = ["param":"param"]
let url = "url"
let response = handler.CallApi(url, param)
print(response.IsSuccess)
print(response.Message!)
我知道我不能像这样使用dataTask方法。这是异步的。 但是我如何在非void函数中调用api并返回其响应数据? 我将ReturnedData json解析为struct然后。 在这种情况下,最好的方法是什么? 感谢
答案 0 :(得分:2)
使用异步完成处理程序
public func callApi(with url : String , parameters : [String : Any], completion: @escaping (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
completion(nil)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
// handle the server error
completion(nil)
return
}
apiResponse.ReturnedData = data
apiResponse.IsSuccess = true
apiResponse.Message = "Succeed"
completion(apiResponse)
})
task.resume()
}
并称之为:
var handler = CommonHandler()
let param = ["param":"param"]
let url = "url"
handler.callApi(with: url, parameters: param) { response in
if let response = response {
print(response.IsSuccess)
print(response.Message!)
}
}
注意:
请遵守变量和函数名称以小写字母开头的命名约定,并使用参数标签以提高可读性。