一个接一个地调用两个Alamofire功能

时间:2017-12-08 10:20:56

标签: ios swift request alamofire

我有User类,其中包含ID属性。我做了Alamofire请求,它满足了这个类(ID值)。当按下一个按钮时,我会发送另一个发送用户ID的Alamofire请求。我在第一次请求中得到7个用户,因此第二次请求完成了第7次。当点击按钮时,我想连续进行该过程,以便当我点击按钮它应该首先请求 - >第二次请求(7次) - >第一次要求 - >第二次请求(7次).....问题是它需要等待第一个请求完成以及所有第二个请求。这样做的最佳方法是什么?我想创建小组,但我不确定。

   func cont_like(){
    for var i in 0..<3{
        let group = DispatchGroup()
        let group2 = DispatchGroup()
        group2.enter()
        group.enter()
        Network.sharedInstance.like_all(completion: {
            group.leave()
        })
        group.enter()
        Network.sharedInstance.get_rec(completion: {response in
            print(response)
            group.leave()
        })

        group.notify(queue: .main){
            print("Both Req Done")
            group2.leave()
        }
    }}

第二次请求:

    func like(sender_id: String, completion: @escaping () -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData(completionHandler: { (response) in
            let jsonData = JSON(response.data!)

            guard response.result.isSuccess else {
                print("Error while fetching tags: \(response.result.error!)")
                return
            }
            if let error = response.error{
                print("Error Occured with Request: \(error)")
            }
            if let matched = jsonData["match"].bool{
                print("Liked!: \(matched)")
                if(matched){

                }
            }else{
                print("There is an error with liking :(")
            }

        })
    }
}

第一次请求:

    func get_rec(completion: @escaping (String?) -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        Alamofire.request(baseUrl + recom, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData(completionHandler: { (response) in
            if response.result.isFailure{
                completion(nil)
                self.delegate?.metaError()
                return
            }else{
                do {
                    let decoder = JSONDecoder()
                    let root = try decoder.decode(Root.self, from: response.data!)
                    SharedUsers.sharedUser.populateData(sender: root.data)
                    print(SharedUsers.sharedUser.users[0].id)
                    self.delegate?.updated()
                    completion("Fetched")
                    self.delegate?.updated()

                } catch {
                    print("error: ", error)
                    completion(nil)
                    self.delegate?.metaError()
                }
            }

        })
    }
    else{
    print("Error")
    }
}

像所有Functon一样:

func like_all(completion: @escaping() -> ()){
        let group2 = DispatchGroup()
        group2.enter()
        for user in SharedUsers.sharedUser.users{
            if let id = user.id{
                let group = DispatchGroup()
                group.enter()
                let when = DispatchTime.now() + 0.5 // change 2 to desired number of seconds
                DispatchQueue.main.asyncAfter(deadline: when) {
                    Network.sharedInstance.like(sender_id: id) { result in
                        group.leave()
                        print(result)
                    }

                }
            }
            else{
                continue
            }
        }
        group2.leave()
        completion()
    }

编辑:我编辑了这些功能,但仍然在不等待所有类似请求的情况下调用第一个请求。

1 个答案:

答案 0 :(得分:0)

有一种不同的方法,一种是DispatchGroup

  let group = DispatchGroup()

    group.enter()
    func like(sender_id: String, completion: @escaping () -> ()){
        group.leave()
    }

    group.enter()
    func get_rec(completion: @escaping (String?) -> ()){
        group.leave()
    }

    group.notify(queue: .main) {
        print("both requests done")
    }

另一个是adDependency的NSOperationQueue。