我正在实现一个API客户端,它将调用我的后端API,并返回相应的对象或错误。
这是我到目前为止所做的:
public typealias JSON = [String: Any]
public typealias HTTPHeaders = [String: String]
public enum RequestMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
public class APIClient {
public func sendRequest(_ url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
let url = URL(string: url)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
if let headers = headers {
urlRequest.allHTTPHeaderFields = headers
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
if let body = body {
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
completionHandler(data, response, error)
}
task.resume()
}
}
好的,我想要做的就是这样:
apiClient.sendRequest("http://example.com/users/1", ".get") { response in
switch response {
case .success(let user):
print("\(user.firstName)")
case .failure(let error):
print(error)
}
}
apiClient.sendRequest("http://example.com/courses", ".get") { response in
switch response {
case .success(let courses):
for course in courses {
print("\(course.description")
}
case .failure(let error):
print(error)
}
}
因此,apiClient.sendRequest()方法必须将响应json解码为所需的swift对象,并返回该对象或错误对象。
我有这些结构:
struct User: Codable {
var id: Int
var firstName: String
var lastName: String
var email: String
var picture: String
}
struct Course: Codable {
var id: Int
var name: String
var description: String
var price: Double
}
我也定义了此结果枚举:
public enum Result<Value> {
case success(Value)
case failure(Error)
}
我被困的地方是,我不知道如何在sendRequest()中调整我的completionHandler,以便我可以将它与User对象或Course对象或任何其他自定义对象一起使用。我知道我必须以某种方式使用泛型来实现这一点,并且我在C#中使用了泛型,但是我在Swift 4中还不太舒服,所以任何帮助都会受到赞赏。
编辑:另外,我想知道sendRequest()的响应如何在ViewController中向一个级别回调到调用代码,以便ViewController可以访问成功和失败结果(在异步时尚)。
答案 0 :(得分:2)
这是一个可以使用的方法,它将实际的HTTP工作转发到现有方法,并仅处理json解码:
public func sendRequest<T: Decodable>(for: T.Type = T.self,
url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<T>) -> Void) {
return sendRequest(url, method: method, headers: headers, body:body) { data, response, error in
guard let data = data else {
return completion(.failure(error ?? NSError(domain: "SomeDomain", code: -1, userInfo: nil)))
}
do {
let decoder = JSONDecoder()
try completion(.success(decoder.decode(T.self, from: data)))
} catch let decodingError {
completion(.failure(decodingError))
}
}
}
,可以像这样调用:
apiClient.sendRequest(for: User.self,
url: "https://someserver.com",
method: .get,
completion: { userResult in
print("Result: ", userResult)
})
,或者像这样:
apiClient.sendRequest(url: "https://someserver.com",
method: .get,
completion: { (userResult: Result<User>) -> Void in
print("Result: ", userResult)
})
,通过指定完成签名并省略第一个参数。无论哪种方式,如果我们提供足够的信息,我们让编译器推断其他东西的类型。
在多种方法之间分配责任使它们更易于重用,更易于维护和理解。
假设你将api客户端包装到另一个暴露一些更通用的方法的类中,隐藏api客户端的复杂性,并允许通过只传递相关信息从控制器调用,你最终会得到一些像这样的方法:
func getUserDetails(userId: Int, completion: @escaping (Result<User>) -> Void) {
apiClient.sendRequest(for: User.self,
url: "http://example.com/users/1",
method: .get,
completion: completion)
}
,可以从控制器中简单地调用,如下所示:
getUserDetails(userId: 1) { result in
switch result {
case let .success(user):
// update the UI with the user details
case let .failure(error):
// inform about the error
}
}
更新通过在sendRequest()
上添加另一个重载,也可以轻松添加对解码数组的支持,以下是从答案开头的代码的小型重构版本:
private func sendRequest<T>(url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<T>) -> Void,
decodingWith decode: @escaping (JSONDecoder) throws -> T) {
return sendRequest(url, method: method, headers: headers, body:body) { data, response, error in
guard let data = data else {
return completion(.failure(error ?? NSError(domain: "SomeDomain", code: -1, userInfo: nil)))
}
do {
let decoder = JSONDecoder()
// asking the custom decoding block to do the work
try completion(.success(decode(decoder)))
} catch let decodingError {
completion(.failure(decodingError))
}
}
}
public func sendRequest<T: Decodable>(for: T.Type = T.self,
url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<T>) -> Void) {
return sendRequest(url,
method: method,
headers: headers,
body:body,
completion: completion) { decoder in try decoder.decode(T.self, from: data) }
}
public func sendRequest<T: Decodable>(for: [T].Type = [T].self,
url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<[T]>) -> Void) {
return sendRequest(url,
method: method,
headers: headers,
body:body,
completion: completion) { decoder in try decoder.decode([T].self, from: data) }
}
现在你也可以这样做:
func getAllCourses(completion: @escaping (Result<[Course]>) -> Void) {
return apiClient.sendRequest(for: User.self,
url: "http://example.com/courses",
method: .get,
completion: completion)
}
// called from controller
getAllCourses { result in
switch result {
case let .success(courses):
// update the UI with the received courses
case let .failure(error):
// inform about the error
}
}