简体   繁体   English

Swift:转义闭包成功后如何将值传递给先前的 ViewController

[英]Swift: Escaping closure How to pass values to previous ViewController after success

I am using @escaping closure to run functions All i want to pass the success dictionary to my previous ViewController to use its data.我正在使用 @escaping 闭包来运行函数 我想将成功字典传递给我以前的 ViewController 以使用它的数据。 Here is my code这是我的代码

func addToCart(vc:UIViewController, param:[String:String], completionHandler:@escaping (_ success:Bool, _ errorC : Error?, _ stock_flag : Bool?) -> Void)
    {
WebServiceHelper.sharedInstanceAPI.hitPostAPI(urlString: KeyConstant.APIAddCart, params: pramaTemp, completionHandler: { (result: [String:Any], err:Error?) in
            print(result)
            MBProgress().hideIndicator(view: vc.view)
            if(!(err == nil))
            {
                completionHandler(false,err, false)
                return
            }
            let json = JSON(result)
            
            let statusCode = json["status"].string
            print(json)
            if(statusCode == "success")
            {
                print(result)
                
                completionHandler(true,err,true)
            }
            else
            {
                if(json["stock_flag"].string == "0")
                {
                    completionHandler(false,err,false)
                }
                else if(json["stock_flag"].int == 0)
                {
                    completionHandler(false,err,false)
                }
                else
                {
                    completionHandler(false,err,true)
                }
            }
        })
        
    }

I got Success in response.我得到了 Success 的回应。 Please guide me how i pass the result data to my previous ViewController .请指导我如何将结果数据传递给我以前的ViewController

I am using this code to navigate to model view where i am using the above code我正在使用此代码导航到我使用上述代码的模型视图

CartViewModel().addToCart(vc: self, param:params ) { (isDone:Bool, error:Error?, stock_flag:Bool?) in

You could add the dictionary to your success closure like this:您可以将字典添加到您的成功闭包中,如下所示:

func addToCart(vc:UIViewController, param:[String:String], completionHandler:@escaping (_ success:Bool, _ errorC : Error?, _ stock_flag : Bool?, result: [String:Any]?) -> Void)
{ ... }

Afterwards you can just use it in the closure.之后你可以在闭包中使用它。

CartViewModel().addToCart(vc: self, param:params ) { (isDone, error, stock_flag, result) in 
    // Use result here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM