0

I passed data from ViewController1 to ViewController2 via segue, but how can I send data to the Class? This class is not a ViewController.

  • ViewController1 has a UIPickerView that gives the data (String).

  • The String will complete an URL needed in ViewController2.

Class

class A: SendDataFromDelegate {

func sendData(data: String) {
    self.data = data
}

var delegate : SendDataFromDelegate?

ViewController1

@IBAction func Picker(_ sender: Any) {
     var delegate: SendDataFromDelegate?
     delegate?.sendData(data: data)
    }

protocol  SendDataFromDelegate {
   func sendData(data : String)
   }

Is this a good way to do it?

Or should I create all the possible URLs in the class, and call them from ViewController2?

Maruta
  • 1,063
  • 11
  • 24
  • Possible duplicate of [Passing Data between View Controllers](https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – Shan Ye Jan 15 '18 at 17:49

1 Answers1

0

You should create a protocol with delegate functions like this:

protocol ClassDelegate: class {
  func doSomething()
}

In your class A you should implement that protocol this way:

class A: ClassDelegate {
  inAFunction(){
    ViewController1.delegate = self
  }

  func sendData(data: String) {
    self.data = data
  }
}

In the viewController you want to send data to your Class A you should have reference of your class A and use the delegate variable:

class ViewController1: UIViewController {
  weak var delegate: ClassDelegate?
  func clickHere(){
    delegate.sendData()
  }
}

When you use clickHere function it triggers Class C sendData function.

Try it ;D

Norolim
  • 926
  • 2
  • 10
  • 25
  • Thank you, somehow I am not able to call the delegate: ViewController1.delegate = self – Maruta Jan 16 '18 at 04:33
  • Do you have an instance of class A in your ViewController1? If so you can do this: `delegate = instanceOfClassA` . You have to link both classes with the delegate to make it work. – Norolim Jan 16 '18 at 07:19