简体   繁体   中英

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. 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. Please guide me how i pass the result data to my previous 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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