在iOS中调用多个服务的更好方法是什么?
对于每个单元格,我有5个不同的服务请求要加载到同一个UItableView中 要做到这一点,最好的方法是什么在iOS中调用多个服务的更好方法是什么?,ios,swift,request,alamofire,Ios,Swift,Request,Alamofire,对于每个单元格,我有5个不同的服务请求要加载到同一个UItableView中 要做到这一点,最好的方法是什么 https://example.com/?api/service1 https://example.com/?api/service2 https://example.com/?api/service3 https://example.com/?api/service4 https://example.com/?api/service5 let url = "https://examp
https://example.com/?api/service1
https://example.com/?api/service2
https://example.com/?api/service3
https://example.com/?api/service4
https://example.com/?api/service5
let url = "https://example.com/?api/service1
Alamofire.request(url, method: .get, parameters:nil encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) // result of response serialization
}
使用不同的服务名称重复相同的Alamofire五次。还有另一种方法可以实现它。看看如何使用执行多个异步请求,并等待它们全部完成
对于您调用的每个任务group.enter()
,当您知道请求已完成时,在其完成处理程序中调用group.leave()
。然后有一个notify方法,它将等待所有请求调用leave
,告诉您它们都已完成
我在操场上创建了一个示例(由于使用了URL,该示例将失败并出现错误)
您可能无法像我一样循环浏览URL,因为每个服务的处理方式可能不同。你需要根据你的需要调整它
关于
DispatchGroups
的更多信息可以在网上找到,例如到目前为止您尝试了什么,以及您到底遇到了什么问题?问题是实现它的最佳方法是什么。我只是坚持对服务调用进行迭代循环,或者有请求数组来实现它。您有什么想法,您自己尝试过哪种方法?有很多可能的方法,你必须缩小你的问题范围。哪种方法更好?请求是否相互依赖?你想让它们在不同的线程上吗?我想调用5个服务,结果需要同时显示。我有令牌的参数和URL的api_名称,但没有更改URL如何向请求传递参数?它真的帮助我提升了你的学习项目!我有一个关于guthub的老项目,可以给你一些关于网络的好提示,你需要将它更新到swift 4,但这应该很容易。检查此文件中的fetch方法。您可以传递参数、标题等
import UIKit
import PlaygroundSupport
let serviceLinks = [
"https://example.com/?api/service1",
"https://example.com/?api/service2",
"https://example.com/?api/service3",
"https://example.com/?api/service4",
"https://example.com/?api/service5"
]
// utility as I've not got alamofire setup
func get(to urlString: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
let url = URL(string: urlString)!
let session = URLSession.shared
let task = session.dataTask(with: url) { data, response, error in
completion(data, response, error)
}
task.resume()
}
let group = DispatchGroup()
for link in serviceLinks {
group.enter() // add an item to the list
get(to: link) { data, response, error in
// handle the response, process data, assign to property
print(data, response, error)
group.leave() // tell the group your finished with this one
}
}
group.notify(queue: .main) {
//all requests are done, data should be set
print("all done")
}
PlaygroundPage.current.needsIndefiniteExecution = true