我要访问Web服务URL十次,并得到响应。我正在使用Alamofire
和SwiftyJSON
。这是我的控制器代码
class ViewController: UIViewController {
let dispatchGroup = DispatchGroup()
var weatherServiceURL = "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22"
override func viewDidLoad() {
super.viewDidLoad()
start()
}
func start() {
weatherService()
dispatchGroup.notify(queue: .main) {
print("All services complete")
}
}
func weatherService() {
for i in 1...10 {
dispatchGroup.enter()
APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
if let error = error {
print(error.localizedDescription)
return
}
guard let response = response else { return }
print("\n\(response) \n\(count) response\n")
self.dispatchGroup.leave()
}
}
}
}
这是我的服务处理程序类代码
class APIManager: NSObject {
class func apiGet(serviceName:String,parameters: [String:Any]?, completionHandler: @escaping (JSON?, NSError?, Int) -> ()) {
Alamofire.request(serviceName, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
let json = JSON(data)
completionHandler(json,nil, parameters!["counter"] as! Int)
}
break
case .failure(_):
completionHandler(nil,response.result.error as NSError?, parameters!["counter"] as! Int)
break
}
}
}
}
我正在发送带有for循环索引的计数器密钥,目的是跟踪返回哪个索引的响应。但是响应不是按顺序进行的。我们可以期望在第二和第一响应之前有第三响应。这是因为带有APIManager.apiGet
函数调用的API调用是异步的,正在转义,因此继续进行for循环。
我也使用了dispatchQueue
let dispatchQueue = DispatchQueue(label: "com.test.Queue", qos: .userInteractive)
并将函数转换为:
func weatherService() {
for i in 1...10 {
dispatchGroup.enter()
dispatchQueue.async {
APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
if let error = error {
print(error.localizedDescription)
return
}
guard let response = response else { return }
print("\n\(response) \n\(count) response\n")
self.dispatchGroup.leave()
}
}
}
}
与服务调用代码异步的结果相同。如果我们做
dispatchQueue.sync {
//service call
}
然后,由于async和dispatchQueue中的网络调用假定任务已完成,因此我们也不会按顺序获得响应。
条件是仅以异步方式运行服务,而不会冻结UI。如果我以同步方式运行服务,那么我会得到理想的结果。但是阻塞主线程是根本不可接受的。
我可以使用数组或某些全局bool变量来管理此事,但我不想使用它们。还有什么其他方法可以使我以被称为的串行顺序获得响应?任何帮助或提示,表示赞赏。
答案 0 :(得分:0)
获得api调用的最简单方法是在上一个的完成处理程序中执行“下一个”调用,而不是在api调用之外使用for
循环。
func weatherService(counter: Int = 1, maxCount: Int = 10) {
guard counter <= maxCount else {
return
}
dispatchGroup.enter()
APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
self.weatherService(counter: counter+1, maxCount: maxCount)
if let error = error {
print(error.localizedDescription)
self.dispatchGroup.leave()
return
}
guard let response = response else {
self.dispatchGroup.leave()
return
}
print("\n\(response) \n\(count) response\n")
self.dispatchGroup.leave()
}
}
}
我建议不要这样做,除非对顺序有某种依赖性(即呼叫2需要来自呼叫1的结果的信息),因为它比并行请求要花费更长的时间。
最好处理结果可能会出现故障的事实。
此外,在使用调度组时,需要确保在代码完成的所有情况下都调用dispatchGroup.leave
;在您的情况下,如果发生错误,则不这样做。如果一个或多个请求中发生错误,这将导致dispatchGroup.notify
永不触发。
答案 1 :(得分:0)
您需要创建带有闭包的容器。此容器将保存所有关闭。容器将检查index1 == index2
是否在 index1 之前和if index1 + 1 > exist
之后运行所有操作。
因此,此容器将检查收到的闭包的顺序,并以升序逐一运行闭包。
Xcode 9.4.1,Swift 4.1
class ActionsRunController {
typealias Func = ()->()
private var actions: [Int: Func] = [:]
private var dispatchSemaphore = DispatchSemaphore(value: 1)
private var firstIndex = 0
private var lastIndex = 0
func add(at index: Int, action: Func?) {
dispatchSemaphore.wait()
actions[index] = action
if lastIndex == index {
while (actions[firstIndex] != nil) {
actions[firstIndex]?()
actions[firstIndex] = nil
firstIndex += 1
}
lastIndex = firstIndex
}
dispatchSemaphore.signal()
}
}
别忘了在此处添加容器的代码
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
let dispatchGroup = DispatchGroup()
var weatherServiceURL = "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22"
override func viewDidLoad() {
super.viewDidLoad()
start()
}
func start() {
weatherService()
dispatchGroup.notify(queue: .main) {
print("All services complete")
}
}
func weatherService() {
for i in 0...9 {
dispatchGroup.enter()
APIManager.apiGet(serviceName: self.weatherServiceURL, counter: i) { (response:JSON?, error:NSError?, count:Int) in
if let error = error {
print(error.localizedDescription)
return
}
//guard let response = response else { return }
print("[executed] action \(count)")
self.dispatchGroup.leave()
}
}
}
}
class APIManager: NSObject {
private static let actionsRunController = ActionsRunController()
class func apiGet(serviceName:String, counter: Int, completionHandler: @escaping (JSON?, NSError?, Int) -> ()) {
Alamofire.request(serviceName, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
//print("[created] action \(counter)")
switch(response.result) {
case .success(_):
if let data = response.result.value{
let json = JSON(data)
actionsRunController.add(at: counter) {
completionHandler(json, nil, counter)
}
}
break
case .failure(_):
actionsRunController.add(at: counter) {
completionHandler(nil,response.result.error as NSError?, counter)
}
break
}
}
}
}
答案 2 :(得分:0)
我决定不保存闭包,而是决定将所有内容包装在分派队列中并在其中使用信号量
//Create a dispatch queue
let dispatchQueue = DispatchQueue(label: "myQueue", qos: .background)
//Create a semaphore
let semaphore = DispatchSemaphore(value: 0)
func weatherService() {
dispatchQueue.async {
for i in 1...10 {
APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
if let error = error {
print(error.localizedDescription)
return
}
guard let response = response else { return }
//print("\n\(response) \n\(count) response\n")
print("\(count) ")
//Check by index, the last service in this case
if i == 10 {
print("Services Completed")
}
//Signals free on service return to work for next service
self.semaphore.signal()
}
//Wait till the service returns
self.semaphore.wait()
}
}
print("Start Fetching")
}