构建我的第一个Swift应用程序并使用Parse作为Baas。 我将它包装在一个服务中,这样我就可以检查数据输入并准备结果......让我的生活更轻松。但我不确定如何使用它进行异步调用。
我通常会让我的服务返回包含success: Bool
,message: String
(错误原因)和data: [AnyObject]
结果的回复。我来自一个JS世界,我习惯于回调,但不知道这是如何工作的,因为块不返回数据......
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)
}
}
我完全错了吗? 任何帮助非常感谢。
答案 0 :(得分:1)
使用Apple在其框架中使用的完成处理程序(块):
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
}