ios - Pass a variable value from an IBAction to an IBOutlet -
ok, new , working through development course. realise if crack 1 long way forwards.
i make post call php file on server , return json data. works. , can print variable
print("firstnamevalue: \(firstnamevalue)")
i want output value of 1 variable...firstnamevalue text field called textfield.
i new swift , thinking "global variable?". worked want wait response http call complete update text field.
i hope can help. new oop , head 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 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 } // 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 server side script nsdictionary object: { let myjson = try nsjsonserialization.jsonobjectwithdata(data!, options: .mutablecontainers) as? nsdictionary if let parsejson = myjson { // can access value of first name key let firstnamevalue = parsejson["firstname"] as? string print("firstnamevalue: \(firstnamevalue)") edit::the below 2 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 = 9 let b = 10 let c = (a*b) textfield.text="you banana \(c)" } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. }
the text field must updated in completion handler because datataskwithrequest
works asynchronously.
this code necessary optional binding checks , runs line update text field on main thread.
... { 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
not needed @ in case.
Comments
Post a Comment