使用alamofire发送POST请求以在我的应用中注册用户后,我尝试根据服务器返回的user_id创建User对象。但是,当我尝试在初始化该用户对象后直接打印该用户对象的某些属性时,它可以正常工作。但是,当我在alamofire发布请求完成执行后尝试打印其某些属性时,我得到的是nil。
import UIKit
import Alamofire
class ViewController: UIViewController {
var user: User!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var phone_number_field: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: Actions
@IBAction func generateQR(_ sender: UIButton) {
let name = nameField.text
let email = emailField.text
let phone_number = phone_number_field.text
let params: Parameters = ["name": name!, "email": email!, "phone_number": phone_number!]
AF.request("http://127.0.0.1:5000/register", method: .post, parameters: params, encoding: JSONEncoding.default).responseString { response in
switch response.result {
case .success:
let user_id = response.result.value
self.user = User(name: name!, email: email!, phone_number: phone_number!, user_id: user_id!)
print(self.user?.name) // <--This print statement works correctly -->
case .failure:
print("Error")
}
}
print(self.user?.name) // <--This prints nil and in the debugger, self.user shows as nil-->
performSegue(withIdentifier: "qrSegue", sender: self)
}
//END Actions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is QRCodeController {
//Pass user object
let qr_controller = segue.destination as? QRCodeController
qr_controller?.user = self.user
}
}
}
答案 0 :(得分:1)
您的服务呼叫是异步的。了解同步与异步方法。
AF向服务器发送了请求,下面的代码继续工作。当您的回复到达时,成功或失败阻止开始起作用。
因此,直到成功块运行,才分配用户对象。
这是解决方法:
AF.request("http://127.0.0.1:5000/register", method: .post, parameters: params, encoding: JSONEncoding.default).responseString { response in
switch response.result {
case .success:
let user_id = response.result.value
self.user = User(name: name!, email: email!, phone_number: phone_number!, user_id: user_id!)
print(self.user?.name) // <--This print statement works correctly -->
performSegue(withIdentifier: "qrSegue", sender: self)
case .failure:
print("Error")
}
}
您可以在页面上显示正在加载的状态,同时等待请求的响应,并在成功时将其隐藏。