我创建了这种基本架构来处理我的网络事务,

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

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 中调用此命令时:
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)
        }
    }

}

Buuut,似乎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 - iOS-Swift 3-DispatchGroup,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41654959/

10-11 20:53