-3

OK, I am new to this and working slowly through a development course. But I realise if I could crack this one I would be a long way forwards.

I make a post call to a PHP file on my server and return the JSON data. This works. and I can print the variable

print("firstNameValue: \(firstNameValue)")

I now want to output the value of one variable...firstNameValue into a text field called textField.

I am new to Swift and I am thinking "global variable?". This worked but I want to wait for the response from the HTTP call to complete then update the text field.

I hope you can help. I am very new to OOP and my head is bursting.

import UIKit 

class ViewController: UIViewController {

    @IBOutlet weak var feel: UITextField!

    @IBAction func anxious(sender: AnyObject) {



        let myUrl = NSURL(string: "http://mywebsite.com/Jamesbond.php");

        let request = NSMutableURLRequest(URL:myUrl!);

        request.HTTPMethod = "POST";// Compose a query string

        let postString = "firstName=James&lastName=Bond";

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil
            {
                print("error=\(error)")
                return
            }

            // You can print out response object
            print("response = \(response)")

            // Print out response body
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")

            //Let's convert response sent from a server side script to a NSDictionary object:
            do {
                let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                if let parseJSON = myJSON {

                    // Now we can access value of First Name by its key
                    let firstNameValue = parseJSON["firstName"] as? String

                    print("firstNameValue: \(firstNameValue)")

                  EDIT::the below two lines solved it.
                    dispatch_async(dispatch_get_main_queue()) {
                    self.textField.text = firstNameValue}


                }
            } catch {
                print(error)
            }
        }
        task.resume()

    }
    @IBOutlet weak var textField: UITextField!




    @IBAction func submit(sender: AnyObject) {
        print("hello")
        let a = 9
        let b = 10
        let c = (a*b)
        textField.text="You are a banana \(c)"

    }




    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
uberphoebe
  • 81
  • 2
  • 8
  • 2
    Just replace the *I WANT TO PUT THIS VALUE...* comment with the code to update the text field and you are done. – vadian Jul 28 '16 at 09:55
  • Thank you that does not work this is the first thing I tried. textField.text="name= \(firstNameValue!)" this comes back with an error – uberphoebe Jul 28 '16 at 10:27
  • It says I neeed to put self. in front like self.textField.text but when I do this it doesn't generate a compile error but no value is inserted in the field. – uberphoebe Jul 28 '16 at 10:34
  • 1
    You might dispatch the line to the main thread. – vadian Jul 28 '16 at 10:50

1 Answers1

0

The text field must be updated in the completion handler because dataTaskWithRequest works asynchronously.

This code does all necessary optional binding checks and runs the line to update the text field on the main thread.

...     
do {
   if let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject],
      firstNameValue = parseJSON["firstName"] as? String {
         print("firstNameValue: \(firstNameValue)")

         dispatch_async(dispatch_get_main_queue()) {
           self.textField.text = firstNameValue
         }
   }
}
catch {
    print(error)
}

The option .MutableContainers is not needed at all in this case.

vadian
  • 274,689
  • 30
  • 353
  • 361