构建我的第一个 Swift 应用程序并使用 Parse 进行 Baas。 我将其包装在一个服务中,以便我可以检查数据输入并准备结果......让我的生活更轻松。但我不确定如何使用异步调用。
我通常让我的服务返回 success: Bool
的响应, message: String
(错误原因)和 data: [AnyObject]
为了结果。我来自 JS 世界,我习惯了回调,但不确定这里是如何工作的,因为 block 不返回数据......
class UserService {
class func register(email: String, password: String) -> Response {
if email == "" || password == "" {
return Response(success: false, message: "Please enter an email and password")
}
var user = PFUser()
user.username = email
user.email = email
user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
// here I would like to return my response success: false, message: errorString
} else {
// Hooray! Let them use the app now.
// Here I would like to return response success: true
}
}
return Response(success: true, message: "")
}
有关信息,以下是我在 ViewController 中调用服务的方式
@IBAction func registerBtn(sender: AnyObject) {
registerBtnBtn.enabled = false
let response: Response = UserService.register(emailInput.text, password: passwordInput.text)
if !response.success {
registerBtnBtn.enabled = true
registerBtnBtn.setTitle("Registering", forState: .Normal)
AlertTools.okAlert(self, title: "Something went wrong...", message: response.message)
} else {
self.performSegueWithIdentifier("registerToBabySegue", sender: self)
}
}
我的做法完全错误吗? 非常感谢任何帮助。
最佳答案
使用 Apple 在其框架中使用的完成处理程序( block ):
typealias Response = (success: Bool, message: String?)
class UserService {
class func register(email: String, password: String, completionHandler: ((Response)->())?) {
if email == "" || password == "" {
completionHandler?(Response(success: false, message: "Please enter an email and password"))
return
}
let user = PFUser()
user.username = email
user.email = email
user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
completionHandler?(Response(success: false, message: errorString))
// here I would like to return my response success: false, message: errorString
} else {
completionHandler?(Response(success: true, message: nil))
// Hooray! Let them use the app now.
// Here I would like to return response success: true
}
}
completionHandler?(Response(success: true, message: nil))
}
}
UserService.register("some@email.com", password: "12345") { (response: Response) -> () in
// process response
}
关于xcode - 使用异步调用创建 Parse 服务以返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32071786/