How to pass data between two ViewController using

2019-09-20 10:52发布

问题:

I want to know how to pass data using closure. I know that there are three types of data pass approaches:

  • delegate

  • Notification Center

  • closure

I want proper clarification of closure with an example.

回答1:

Well passing data with blocks / closures is a good and reasonable approach and much better than notifications. Below is the same code for it.

First ViewController (where you make object of Second ViewController)

 @IBAction func push(sender: UIButton) {
        let v2Obj = storyboard?.instantiateViewControllerWithIdentifier("v2ViewController") as! v2ViewController

        v2Obj.completionBlock = {(dataReturned) -> ()in
            //Data is returned **Do anything with it **
            print(dataReturned)
        }
        navigationController?.pushViewController(v2Obj, animated: true)

    }

Second ViewController (where data is passed back to First VC)

import UIKit
typealias v2CB = (infoToReturn :String) ->()
class v2ViewController: UIViewController {
        var completionBlock:v2CB?
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func returnFirstValue(sender: UIButton) {
        guard let cb = completionBlock else {return}
        cb(infoToReturn: returnFirstValue)
    }

}


回答2:

This example explains use of service call with Alamofire and send the response back to calling View Controller with closure.

Code in Service Wrapper Class:

Closure declaration

typealias CompletionHandler = (_ response: NSDictionary?, _ statusCode: Int?, _ error: NSError?) -> Void

Closure implementation in method

    func doRequestFor(_ url : String, method: HTTPMethod, dicsParams : [String: Any]?, dicsHeaders : [String: String]?, completionHandler:@escaping CompletionHandler) {

        if !NetworkReachablity().isNetwork() {
            return
        }

        if (dicsParams != nil) {print(">>>>>>>>>>>>>Request info url: \(url) --: \(dicsParams!)")}
        else {print(">>>>>>>>>>>>>Request info url: \(url)")}

        Alamofire.request(url, method: method, parameters: dicsParams, encoding:
            URLEncoding.default, headers: dicsHeaders)

        .responseJSON { response in
            self.handleResponse(response: response, completionHandler: completionHandler)
        }
    }

Code at calling view controller:

        ServiceWrapper().doRequestFor(url, method: .post, dicsParams: param, dicsHeaders: nil) { (dictResponse, statusCode, error) in

        }