gpt4 book ai didi

ios - Swift:一个接一个地发送网络请求

转载 作者:行者123 更新时间:2023-12-01 19:35:59 31 4
gpt4 key购买 nike

我想一个接一个地发送请求。等待第一个响应发送第二个。

目前我使用这个:

DispatchQueue.global().async {
let dispatchGroup = DispatchGroup()

dispatchGroup.enter()
self.requestOne { _ in
dispatchGroup.leave()
}
dispatchGroup.wait()


dispatchGroup.enter()
self.requestTwo { _ in
dispatchGroup.leave()
}
dispatchGroup.wait()


dispatchGroup.enter()
self.requestTree { _, url in
user.profileImage = url?.absoluteString
dispatchGroup.leave()
}
dispatchGroup.wait()


self.requestFour { error in
completion(error)
}
}

它工作得很好,但我想知道是否有办法在不使用的情况下让这个更清洁、更快捷
dispatchGroup.enter()
dispatchGroup.leave()
dispatchGroup.wait()

甚至是在类中包装逻辑的模式

最佳答案

利用组合的简单网络层

这个答案深受 this post 的影响。 .我尽可能删除了不必要的代码,并在需要的地方添加了代码来组成一个工作的游乐场。

Api 无关层部分

import Foundation
import Combine

struct Agent {

func run<T: Decodable>(_ request: URLRequest, _ decoder: JSONDecoder = JSONDecoder()) -> AnyPublisher<T, Error> {
return URLSession.shared
.dataTaskPublisher(for: request)
.tryMap { result -> T in
return try decoder.decode(T.self, from: result.data)
}
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}

Api相关层部分
enum GithubAPI {
static let agent = Agent()
static let base = URL(string: "https://api.github.com")!
}

extension GithubAPI {

static func repos(username: String) -> AnyPublisher<[Repository], Error> {
let request = URLRequest(url: base.appendingPathComponent("users/\(username)/repos"))
return agent.run(request)
}

struct Repository: Codable {
let node_id: String
let name: String
}

static func issues(repo: String, owner: String) -> AnyPublisher<[Issue], Error> {
let request = URLRequest(url: base.appendingPathComponent("repos/\(owner)/\(repo)/issues"))
return agent.run(request)
}

struct Issue: Codable {
let url: URL
}

}

您正在寻找的实际干净和快速的代码

请注意,发行请求取决于 repo 请求。实际请求由接收器调用触发。
let user = "Alamofire"
let repos = GithubAPI.repos(username: user)
let firstRepo = repos.compactMap { $0.first }
let issues = firstRepo.flatMap { repo in
GithubAPI.issues(repo: repo.name, owner: user)
}
let token = issues.sink(receiveCompletion: { (_) in }) { (issues) in
print(issues)
}

关于ios - Swift:一个接一个地发送网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152082/

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