我如何从AlamoFire返回一些东西? [英] How do I return something from AlamoFire?
本文介绍了我如何从AlamoFire返回一些东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import Foundation
import Alamofire
import UIKit
import SwiftyJSON
class APIClient: UIViewController {
let loggedIn = false
struct Constants{
static let Domain = "http://gogogo.com"
}
func authenticate() -> Bool{
println("Authenticating")
if let access_token = FBSDKAccessToken.currentAccessToken().tokenString {
let parameters = [ "access_token": access_token ]
Alamofire.request(.POST, Constants.Domain+"/accounts", parameters: parameters).responseJSON {
(req, res, json, error) in
if(error != nil) {
self.sendReturnToSplash()
} else {
let json = JSON(json!)
println("\(json)")
return true //This doesn't work!!!!!!
}
}
}else{
println("No access token to authenticate")
}
}
func sendReturnToSplash(){
let center = NSNotificationCenter.defaultCenter()
let notification = NSNotification(name: NotificationCenters.ReturnToSplash, object: self, userInfo: ["":""])
center.postNotification(notification)
}
}
如你所见,如果注销成功,我想返回true。但是,XCode给了我一个Void不符合协议BooleanLiteral
As you can see, if the log out is successful, I want to return "true". However, XCode gives me a "Void does not conform to protocol BooleanLiteral"
推荐答案
由于你正在使用异步调用,你应该将您的身份验证功能视为异步。我建议使用类似于以下内容的完成块:
Since you are using an asynchronous call, you should treat your authenticate function as asynchronous. I suggest using a completion block similar to the following:
func authenticate(completion:(success: Bool) -> Void) {
println("Authenticating")
if let access_token = FBSDKAccessToken.currentAccessToken().tokenString {
let parameters = [ "access_token": access_token ]
Alamofire.request(.POST, Constants.Domain+"/accounts", parameters: parameters).responseJSON { (req, res, json, error) in
if error != nil {
self.sendReturnToSplash()
completion(success: false)
} else {
let json = JSON(json!)
println("\(json)")
completion(success: true)
}
}
} else {
println("No access token to authenticate")
completion(success: false)
}
}
这篇关于我如何从AlamoFire返回一些东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文