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.
}