Home > Software engineering >  I can't use Delegate and Protocol to pass data
I can't use Delegate and Protocol to pass data

Time:02-04

I Learn Swift, I want to pass Json api data to viewController using delegate and protocol:

In viewController:

  class exchangeViewController: UIViewController { 

var exchange = Exchange(baseUri: "http://data.fixer.io/api/latest?access_key=", apiKey: "apiKey")
@IBOutlet weak var inputEuro: UITextField!
@IBOutlet weak var getDollar: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    
    exchange.delegate? = self
}

@IBAction func exchangeCurrency(_ sender: UIButton) {
    print("button1")
    exchange.fitchData()
    print("button2")
} }


extension exchangeViewController: ExchangeCurrencyDelegate {
func didRetriveDollarvalue(dollar: Dollar) {
  
        print(dollar.base   " e1")
        self.getDollar.text = dollar.base
        print(dollar.base   " e2")
      }       
   }

in Model Class:

protocol ExchangeCurrencyDelegate{
func didRetriveDollarvalue(dollar: Dollar)    }

class Exchange{
var delegate : ExchangeCurrencyDelegate?
var baseUri : String
var apiKey  : String

init(baseUri: String, apiKey: String){
    self.baseUri = baseUri
    self.apiKey = apiKey
}
func fitchData(){
    
    let url = URL(string: baseUri   apiKey)
    
    let session = URLSession(configuration: .default)
    
    let task = session.dataTask(with: url!, completionHandler: taskHandler(data:urlresponse:error:))
    
    task.resume()
}

func taskHandler(data: Data?, urlresponse: URLResponse?, error: Error?) -> Void{
    do {
        
        let dollarValue:Dollar = try JSONDecoder().decode(Dollar.self, from: data!)
       
            print(dollarValue.base   " a")
            delegate?.didRetriveDollarvalue(dollar: dollarValue)
            print(dollarValue.base   " b")
     
        
    }
    catch {
        print(error)
    }
}  }

In Dollar Struct:

struct Dollar: Decodable{
var base: String }

when i execute this app, i can print: button1, button2, dollarValue.base " a", dollarValue.base " b", but i can't execute didRetriveDollar protocol in extension exchangeViewController.

when i use Breakpoint, The program goes beyond delegate?.didRetriveDollarvalue(dollar: dollarValue) in model class. Can anyone find where is my wrong? Thank you I am sorry if my level in english isn't good enough.

CodePudding user response:

It seems you are not setting your Exchange delegate correctly within your viewDidLoad method:

exchange.delegate? = self

Try changing it to:

exchange.delegate = self

CodePudding user response:

for solve this error, I deleted "?" from exchange.delegate? = self, and i added : DispatchQueue.main.async {.....}. This answer make the code work. thank you

  •  Tags:  
  • Related