gpt4 book ai didi

urlsession - 如何使用 swift 5 URLSession 中引入的新 Result 类型?

转载 作者:行者123 更新时间:2023-12-03 23:36:11 29 4
gpt4 key购买 nike

Swift 5 引入了新的 Result 类型来处理异步函数的结果。我想知道如何将这种新的结果类型用于 URLSession。

I have this following code.


func getCategorByAPI()
{
//Base Url is from an static variable
let url = URL(string: URLManager.aPIBaseURL+"category")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
//print("error=\(error)")
return
}

do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json)
}catch
{
print(error)
}

}

task.resume()
}

如何使用 swift 5 Result 类型重写此函数?

最佳答案

您要创建一个 enum指定结果中可能的情况(例如成功或失败)。然后你添加一个完成到你的 getCategorByAPI()类型为 Result<Data, Error> 的方法.从那里,在 url session 中,您将调用您的完成处理程序,传入 data.successerror.failure .

你也可以做一些很酷的事情,比如覆盖 Result 的 get()方法和扩展 Result解码您的数据:D

一探究竟:

enum Result<Success, Error: Swift.Error> {
case success(Success)
case failure(Error)
}

// override the Result.get() method
extension Result {
func get() throws -> Success {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
}

// use generics - this is where you can decode your data
extension Result where Success == Data {
func decoded<T: Decodable>(using decoder: JSONDecoder = .init()) throws -> T {
let data = try get()
return try decoder.decode(T.self, from: data)
}
}


func getCategorByAPI(completion: (Result<Data, Error>) -> Void)
{
// You might want to stick this into another method
let url = URL(string: URLManager.aPIBaseURL+"category")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
completion(.failure(error))
return
}

if !(200...299).contains(httpResponse.statusCode) && !(httpResponse.statusCode == 304) {
let httpError = // ... convert httpResponse.statusCode into a more readable error
completion(.failure(httpError))
}

if let data = data {
completion(.success(data))
}
}.resume()
}

我还没有测试上述内容,但在当前项目中实现了类似的内容。以下是我阅读的一些文章,以了解如何实现:
https://www.hackingwithswift.com/articles/161/how-to-use-result-in-swift
https://medium.com/@pavlepesic/how-to-use-swift-5-result-with-codable-protocol-824c9a951af9

关于urlsession - 如何使用 swift 5 URLSession 中引入的新 Result 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847474/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com