Search code examples
iosswiftgrand-central-dispatch

Dispatch Group wait till Timeout


I use the following function to fetch data from an api, however what I am struggling to do is timing out the function when the set time runs out.

My objective:

-I want the following code to wait for some time, e.g. 10 seconds and if 10 seconds have passed, I want it to continue with other functions and work i.e. not keep on waiting. For that I am using dispatchgroup wait method. However it is not working as intended. How do I adjust the following to achieve that?.


class ViewController: UIViewController {

    var myArr = [testing]()
    let dispatchGROUP=DispatchGroup() 
. . .}
    @objc func warmUp(url: String, u: String, p: String){
    

        let waitResult = dispatchGROUP.wait(timeout: .now() + 10)

        AF.request(url, method: .get)
            .authenticate(username: u, password: p)
            .response { [weak self] response in

                guard let safeData = response.data else {self?.sArr.append("0")/*; self?.warm.leave()*/; print("0 sent"); print(url,u,p); return}
                let xml = XML.parse(safeData)
                let sid = xml.Response.SID.text ?? ""
                print(sid)
                self?.sArr.append(sid)
//                self?.dispatchGROUP.leave()
                if waitResult == .success{
                    print("success")
                    self?.dispatchGROUP.leave()
                }else if waitResult == .timedOut{
                    print("fail")
                    self?.dispatchGROUP.leave()
                    return
                }
            }
    }

Solution

  • stackoverflow.com/a/61192412/1801544 Please set timeout interval, I believe this is what you want