ios - Swift Callback change UIViewController Label -
i started study swift ios yesterday , i'm trying make simple login app. swift file
import foundation import swifthttp func printsomething (sentence: string) { println(sentence); } func makelogincall(user: string, pwd: string, donefunction : (bool) -> void) { var url : string = "myurl" var request = httptask() request.requestserializer = jsonrequestserializer() request.responseserializer = jsonresponseserializer() request.post(url, parameters : ["username": user, "password": pwd], success: {(response: httpresponse) in if let dict = response.responseobject as? dictionary<string, anyobject> { println("\(dict)") donefunction(true) } }, failure: {(error: nserror, response: httpresponse?) in println("error \(error)") donefunction(false) }) }
and viewcontroller
import uikit class viewcontroller: uiviewcontroller { @iboutlet weak var usertextfield: uitextfield! @iboutlet weak var passtextfield: uitextfield! @iboutlet var resultlabel: uilabel! override func viewdidload() { super.viewdidload() } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } @ibaction func loginbuttoncallback(sender: anyobject) { checklogin() } func checklogin() { var user : string = usertextfield.text var pass : string = passtextfield.text makelogincall(user, pass, printresult) } func printresult(result: bool) -> void { println("print result function started") if (result) { resultlabel.text = "login done" } else { resultlabel.text = "login wrong" } } }
now printresult function called label won't change. what's problem?
your printresult
function runs asynchronously.
all ui changes must dispatched main queue
to main queue use:
dispatch_async(dispatch_get_main_queue(), ^{ donefunction(…) });
inside completion block of post request
Comments
Post a Comment