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")
        }
    }
}
5
  • hmm Im a bit confused about what you want. can you please upload your code? Commented Aug 27, 2017 at 1: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. Commented Aug 27, 2017 at 4:22
  • Possible duplicate of How to pass prepareForSegue: an object Commented Aug 27, 2017 at 4:59
  • Voting to close, passing a ViewModel/data to another ViewController is well answered on Stackoverflow already Commented Aug 27, 2017 at 4: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. Commented Aug 27, 2017 at 8:31

1 Answer 1

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")
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.