How to run synchronically two functions with async operations on iOS using Swift

前端 未结 3 1817
庸人自扰
庸人自扰 2021-02-03 13:12

lets propose this scenario

a method with async network operations

func asyncMethodA() -> String?
{
   result : String?
   Alamofire.manager.request(.P         


        
3条回答
  •  臣服心动
    2021-02-03 13:26

    With the below, you can launch both async methods at the same time and do your heavy lifting after whichever one finishes last.

    var methodAFinished = false
    var methodBFinished = false
    
    func asyncMethodA() -> String?
    {
        Alamofire.manager.request(.POST, "https://www.apiweb.com/apimethod", parameters: parameters, encoding:.JSON)
            .response { (request, response, rawdata, error) in
                if (response?.statusCode == 200) {
                    methodAFinished = true
                    doStuff()
                }
            }
        return result //string
    }
    

    The guts of asyncMethodB would be methodBFinished = true; doStuff()

    func doStuff() {
        if methodAFinished && methodBFinished {
            // do crazy stuff
        }
    }
    

提交回复
热议问题