How do I return something from AlamoFire?

强颜欢笑 提交于 2019-12-01 08:44:51

问题


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)
    }
}

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"


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/29452563/how-do-i-return-something-from-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!