iOS - swift 3 - DispatchGroup

后端 未结 2 928
梦毁少年i
梦毁少年i 2021-01-24 04:46

I created this basic architecture to handle my networking stuff,

i wanted to keep it modular and structured:

public class NetworkManager {

    public pr         


        
相关标签:
2条回答
  • 2021-01-24 04:55

    Change your code as shown below.

    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() // This statement has been moved
            }
        }
    }
    

    The mistake was that you were leaving the DispatchGroup soon after you entered it. If you have to wait for your network operation to complete, you should leave from within the response handler.

    0 讨论(0)
  • 2021-01-24 05:10

    I think you need to put self.dispatchGroup.leave() inside the Alamofire response handler. As written, you leave as soon as you queue the request.

        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()
            }
        }
    
    0 讨论(0)
提交回复
热议问题