2

I am building a simple app that talks to a web service.

I have used the delegates method to communicate data (from my model to view controller).

But I am not sure how to read the data from view controller (text_field.text) in my model. I need to do that so that I can pass the right parameter to my webservice

my view controller is:

import UIKit

class ViewController: UIViewController,HomeModelDelegate {
    var homeModel = HomeModel()

    @IBOutlet weak var loginid: UITextField!
    @IBOutlet weak var pwd: UITextField!

    @IBAction func submit(_ sender: UIButton) {

        homeModel.chkpwd()
        //Here viewcontroller is assigning itself to the homemodel's delegate property
        homeModel.delegate = self            
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        loginid.layer.cornerRadius=10
        pwd.layer.cornerRadius = 10
    }

    func itemsDownloaded(locations: [Location]) {
        loginid.text = locations[0].pwd
    }
}

My model code is:

import UIKit

protocol HomeModelDelegate{
    func itemsDownloaded(locations:[Location])
}

class HomeModel: NSObject
{
    var delegate:HomeModelDelegate?

    func chkpwd()
    {
        //Hit the webservice url

        let x = ViewController()
        let z = x.loginid

        let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"

        //download the json data


        let url = URL(string: serviceUrl)

        if let url = url {

            let session = URLSession(configuration: .default)
            let task = session.dataTask(with: url, completionHandler:
            { (data, response, error) in

                if error == nil {

                //succeeded
                self.parseJson(data!)

                }
                else {
                //failed

                }
            })
        task.resume()

        }
    }

    func parseJson(_ data:Data){

        var locArray = [Location]()

        do{
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
            for jsonResult in jsonArray{

                let jsonDict = jsonResult as! [String:String]
                let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)

                locArray.append(loc)

                //pass the location back to the delegate

                delegate?.itemsDownloaded(locations: locArray)

            }
        }
        catch{
        print("An error occured")
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
coderatlarge
  • 577
  • 3
  • 8
  • 23
  • hmm Im a bit confused about what you want. can you please upload your code? – Siyavash Aug 27 '17 at 01:43
  • I think I understand what you want to do but it would be better if you read the text of your view in the view controller and when yo call chkpwd(), you should send the text as parameter, if that's what you need, i can show code about that, if not, maybe you need to explain better what you're trying to do. – Christian Serrano Aug 27 '17 at 04:22
  • Possible duplicate of [How to pass prepareForSegue: an object](https://stackoverflow.com/questions/7864371/how-to-pass-prepareforsegue-an-object) – Brian Ogden Aug 27 '17 at 04:59
  • Voting to close, passing a ViewModel/data to another ViewController is well answered on Stackoverflow already – Brian Ogden Aug 27 '17 at 04:59
  • @Hitesh, while I have approved your edit, it wasn't very good: you shall not markup as code what isn't a piece of code, like _delegates_. Also, while re-indenting, you left `import UIKit` over-indented and `let x = ViewController()` under-indented. – Cœur Aug 27 '17 at 08:31

1 Answers1

3

Please try this :

import UIKit

class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()

@IBOutlet weak var loginid: UITextField!

@IBOutlet weak var pwd: UITextField!

@IBAction func submit(_ sender: UIButton) {

    homeModel.z = loginid.text! // ASSIGNING z here
    homeModel.chkpwd()
    //Here viewcontroller is assigning itself to the homemodel's delegate property
    homeModel.delegate = self

}

override func viewDidLoad() {
    super.viewDidLoad()
    loginid.layer.cornerRadius=10
    pwd.layer.cornerRadius = 10

}

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

func itemsDownloaded(locations: [Location]) {
    loginid.text = locations[0].pwd

}
}

Model :

import UIKit

protocol HomeModelDelegate{
    func itemsDownloaded(locations:[Location])
}

class HomeModel: NSObject
{
    var z:String = "" // INITIALIZING z
    var delegate:HomeModelDelegate?

    func chkpwd()
    {
        print(z) // CALLING z 
        //Hit the webservice url
        let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"

        //download the json data

        let url = URL(string: serviceUrl)
        if let url = url {
            let session = URLSession(configuration: .default)
            let task = session.dataTask(with: url, completionHandler:
                { (data, response, error) in
                    if error == nil {
                        //succeeded
                        self.parseJson(data!)
                    } else {
                        //failed
                    }
                })
            task.resume()
        }
    }

    func parseJson(_ data:Data){
        var locArray = [Location]()
        do{
            let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
            for jsonResult in jsonArray{
                let jsonDict = jsonResult as! [String:String]
                let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
                locArray.append(loc)

                //pass the location back to the delegate
                delegate?.itemsDownloaded(locations: locArray)
            }
        } catch {
            print("An error occured")
        }
    }
}
Vini App
  • 7,339
  • 2
  • 26
  • 43