gpt4 book ai didi

iOS - swift 3 - DispatchGroup

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:21 25 4
gpt4 key购买 nike

我创建了这个基本架构来处理我的网络问题,

我想让它保持模块化和结构化:

public class NetworkManager {

public private(set) var queue: DispatchQueue = DispatchQueue(label: "com.example.app.dispatchgroups", attributes: .concurrent, target: .main)
public private(set) var dispatchGroup: DispatchGroup = DispatchGroup()

private static var sharedNetworkManager: NetworkManager = {
let networkManager = NetworkManager()
return networkManager
}()

private init() {}

class func shared() -> NetworkManager {
return sharedNetworkManager
}

public func getData() {
dispatchGroup.enter()

queue.async(group: dispatchGroup) {
Alamofire.request(Content.url).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
// do some stuff and save to Content struct
Content.annotations += [Station(...)]

case .failure(let error):
print("error: ",error)
}
}

self.dispatchGroup.leave()
}
}

}

struct Content {

static var url = "url"

static var annotations = [Station]()

}

所以当我在单独的类中调用它时:

class MainViewController {

override func viewDidLoad() {
super.viewDidLoad()

// some stuff ...

NetworkManager.shared().getData()

NetworkManager.shared().dispatchGroup.notify(queue: DispatchQueue.main) {
self.mapView.removeAnnotations(Content.annotations)
self.mapView.addAnnotations(Content.annotations)
}
}

}

但是,似乎在所有请求完成之前执行了 DispatchGroup().notify()...因为没有向 mapview 添加注释。

我已经检查并加载了注释。

有人可以帮我解决这个架构吗?

谢谢和问候!

最佳答案

我认为您需要将 self.dispatchGroup.leave() 放入 Alamofire 响应处理程序中。正如所写,您在排队请求后立即离开。

    queue.async(group: dispatchGroup) {
Alamofire.request(Content.url).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
// do some stuff and save to Content struct
Content.annotations += [Station(...)]

case .failure(let error):
print("error: ",error)
}
self.dispatchGroup.leave()
}
}

关于iOS - swift 3 - DispatchGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654959/

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