使用委托将数据从视图控制器传递到视图控制器

时间:2017-08-01 20:59:08

标签: swift delegates alamofire

尝试将数据从一个视图控制器(从alamofire请求)发送到导航控制器中的下一个视图控制器。

我和一位代表试图这样做,但我没有让它发挥作用。我已经知道这不是方法,但我需要找到一个解决方案让它工作。

从发送变量标题的视图控制器中查看代码:

protocol SendDataToScanInfo {
    func sendData (vendorname01 : String,  productname01: String, productstatus01: String, productdescription01: String)
}

class ScanController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, CLLocationManagerDelegate{

var delegate:SendDataToScanInfo?

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { 

Alamofire.request(URL_SCAN_ID, method: .post, parameters: ScanParameters, encoding: JSONEncoding.default) .responseJSON
                {

                    response in

                    //printing response
                    print(response.request!)
                    print(response.response!)
                    print(response.data!)
                    print(response.result)
                    print(response.error)

                    //getting the json value from the server
                    let value = response.result.value
                    print(value!)
                    let json = JSON(value!)

                    let productdesc0:JSON = json["productdesc"]
                    let productdescString = productdesc0.string


                    let productname0:JSON = json["productname"]
                    let productnameString = productname0.string


                    let tagstate0:JSON = json["tagstate"]
                    let tagstateString = tagstate0.string


                    let vendorname0:JSON = json["vendorname"]
                    let vendornameString = vendorname0.string


                    //self.performSegue(withIdentifier: "ScanInfo", sender: productdescString)
                    self.delegate?.sendData(vendorname01: vendornameString!, productname01: productnameString!, productstatus01: tagstateString!, productdescription01: productdescString!)




                    print(vendornameString)
                }
            if code != nil
            {
                let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let destination = mainStoryboard.instantiateViewController(withIdentifier: "ScanInfo")
                navigationController?.pushViewController(destination, animated: true)
            }

            captureSession.stopRunning();
            //self.dismiss(animated: true, completion: nil)
        }
    }
}

下一个Viewcontroller应该收到它:

class ScanInfoViewController: UIViewController, SendDataToScanInfo {



    @IBOutlet weak var Vendor: UILabel!
    @IBOutlet weak var VendorScan: UILabel!
    @IBOutlet weak var Product: UILabel!
    @IBOutlet weak var ProductScan: UILabel!
    @IBOutlet weak var Status: UILabel!
    @IBOutlet weak var DescriptionScan: UILabel!
    @IBOutlet weak var Description: UILabel!
    @IBOutlet weak var StatusScan: UILabel!



    override func viewDidLoad() {
        super.viewDidLoad()
        DescriptionScan.text = descriptionBLA
        print("jddjd", descriptionBLA)
        let URL_SCAN_INFO = "http://makeitrain.get-legit.com:8998/checktag"

        // Do any additional setup after loading the view.

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func sendData(vendorname01: String, productname01: String, productstatus01: String, productdescription01: String) {
        VendorScan.text = vendorname01
        ProductScan.text = productname01
        DescriptionScan.text = productdescription01
        StatusScan.text = productstatus01
        print("MMMM", StatusScan.text)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ScanInfo" {
            let sendingVC: ScanController = segue.destination as! ScanController
            sendingVC.delegate = self
        }
    }
}

我希望有人可以帮助我!

3 个答案:

答案 0 :(得分:0)

为了传递数据,就像williej926所说,segues是要走的路。要将数据从一个视图控制器传递到另一个视图控制器,您需要在这两个视图控制器之间创建一个segue,如果项目中有多个用于传递数据的segue,则为segue提供一个标识符,这是必须的。在第一个视图控制器的类中,您应该使用内置的方法创建prepareForSegue方法。在prepareForSegue方法中,如果segue的标识符等于您在故事板中设置的标识符,则可以编写。在那个if语句中,你需要告诉这个viewcontroller你的segue的目的地是什么。为此,请编写let destination = segue.destination as! nextViewControllerClass.要访问变量并在第二个viewcontroller中设置它们,请编写destination.variableName = thisVariableName。这是一个示例,向您展示纯粹代码中的内容。

在First View Controller的类中

class FirstViewController: UIViewController {

var thisString: String?

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let identifier = segue.identifier {
                if(identifier == "secondViewController") {
                    let destination = segue.destination as! SecondViewController//SecondViewController is second view controller's class
                    destination.myString = thisString
            }
        }
    }
}

第二个视图控制器的类

class SecondViewController: UIViewController {
     var myString: String?//this will equal to thisString in FirstViewController
}

答案 1 :(得分:0)

wrote an answer关于这个不久前:

  

将信息从一个VC传递到另一个VC的简单方法是通过initiliazer,或者通过在呈现第二个VC之前设置的变量。

secone方法会让你通过一个委托,主要是在将数据传递给初始VC时。无论哪种方式,您都需要类似于此的设置:

class LoggedInVCViewController : UIViewController {

    var info : String? {
       didSet {
          if let newInfo = self.info {
             //do what ever you need to do here
          }
       }
    }

    override viewDidLoad() {
       super.viewDidLoad()

    }

}

func presentLoggedInScreen(yourInfo: String) { 
   let stroyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
   let loggedInVC:LoggedInVCViewController = 
   storyboard.instantiateViewController(withIdentifier: "loggedInVC") as! 
   LoggedInVCViewController 
   loggedInVC.info = yourInfo
   self.present(loggedInVC, animated: true, completion: nil) 
}
class LoggedInVCViewController : UIViewController {

    var info : Any? {
        get {
            if let this = self.info {
                return this
            } else {
                return nil
            }
        } set {
            if let new = newValue {
                //
            }
        }
    }

    init(info: Any?) {
        //This first line is key, it also calls viewDidLoad() internally, so don't re-write viewDidLoad() here!!
        super.init(nibName: nil, bundle: nil)

        if let newInfo = info {
            //here we check info for whatever you pass to it
            self.info = newInfo
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

然后使用:

func presentLoggedInScreen(yourInfo: String) {
        let loggedInVC = LoggedInVCViewController(info: yourInfo)
        self.present(loggedInVC, animated: true, completion: nil)
}

或者,如果您正在使用变量方法:

func presentLoggedInScreen(yourInfo: String) {
        let loggedInVC = LoggedInVCViewController() 
        loggedInVC.info = yourInfo
        self.present(loggedInVC, animated: true, completion: nil)
}

我也会过去,并链接到其他帖子,其中讨论使用Storyboard的注意事项,以及传递数据的自定义初始化程序。我也读过它们了!

答案 2 :(得分:-1)

最好的方法是使用segue。在控制器之间连接一个segue,在prepareForSegue中添加一个代表您正在调整的控制器的变量,如下所示:let viewController = segue.destination as! viewController。现在,您可以使用viewController访问和更改viewController.variable内的变量。