我昨天开始为IOS学习Swift,我试图制作一个简单的登录应用程序。这是我的快速文件
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)
})
}
这是我的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 any resources that can be 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"
}
}
}
现在调用了printResult函数,但标签不会改变。 问题是什么?
答案 0 :(得分:2)
在主线程中编写代码,这将与UI进行交互,如下所示:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if (result) {
resultLabel.text = "Login done"
} else {
resultLabel.text = "Login wrong"
}
})
答案 1 :(得分:1)
您的printResult
函数异步运行。
必须将所有UI更改分派到主队列
要返回主队列,请使用:
dispatch_async(dispatch_get_main_queue(), ^{
doneFunction(…)
});
在POST请求的完成块中