【发布时间】:2015-09-07 23:03:06
【问题描述】:
我正在构建一个 iOS 应用程序,我刚刚完成了我的登录/注册部分(请求一个sails.js rest Api) 目前我有 2 个带有重复代码的视图控制器,因为我在每个类的注册/登录按钮事件侦听器上发出了其余调用,并且我可以重构很多类似的代码。
我想做的是创建一个名为 ApiManager 的单例,它将包含我需要的所有调用。 (以及未来的)
问题在于,使用异步调用我无法创建一个函数 func login(username,password) 来返回数据,以便我可以存储它们并准备继续。
正确实现这一目标的简单/正确方法是什么?这意味着调用 ApiManager.myFunction 并在任何需要的地方使用结果(为数据填充表格视图,启动登录 segue 或注册成功)并使此函数可在另一个视图控制器中重用,即使它用于其他用途。我正在使用 swift。
编辑:这是我的做法,希望对您有所帮助
执行其余调用的函数:
func login(#username: String, password: String, resultCallback: (finalresult: UserModel!,finalerror:String!) -> Void) {
Alamofire.request(.POST, AppConfiguration.ApiConfiguration.apiDomain+"/login", parameters: ["username": username,"password": password], encoding: .JSON)
.responseJSON { request, response, data, error in
if let anError = error
{
resultCallback(finalresult: nil,finalerror:anError.localizedDescription)
}else if(response!.statusCode == 200){
var user:UserModel = self.unserializeAuth(data!)//just processing the json using SwiftyJSON to get a easy to use object.
resultCallback(finalresult: user,finalerror:nil)
}else{
resultCallback(finalresult: nil,finalerror:"Username/Password incorrect!")
}
}.responseString{ (request, response, stringResponse, error) in
// print response as string for debugging, testing, etc.
println(stringResponse)
}
}
这就是我从 ViewController 调用此函数的方式:
@IBAction func onLoginTapped(sender: AnyObject) {//When my user tap the login button
let username = loginInput.text;//taking the content of inputs
let password = passwordInput.text;
ApiManager.sharedInstance.login(username:username,password:password){
[unowned self] finalresult,finalerror in
if(finalresult !== nil){//if result is not null login is successful and we can now store the user in the singleton
ApiManager.sharedInstance.current_user=finalresult
self.performSegueWithIdentifier("showAfterLogin", sender: nil)//enter the actual app and leave the login process
}else{
self.displayAlert("Error!", message: finalerror)//it is basically launching a popup to the user telling him why it didnt work
}
}
}
【问题讨论】:
标签: swift ios8 sails.js alamofire swifty-json