嵌套 Alamofire 回调或全局使用的 return 值

Nesting Alamofire callbacks or return value for Global Usage

我目前正在尝试嵌套 Alamofire 请求以使用我已经使用 GET 请求成功接收到的数据。

对于这段代码,我在这个问题中使用了 Rob 的回答

How to return value from Alamofire

但是,我既不能嵌套 Alamofire 请求,也不能单独使用它们。

这就是我想要做的

override func viewDidLoad() {
    super.viewDidLoad()


    var currentFoodType: String = ""
    var currentFoodList: String = ""

    //debug

    //this is how I get back the token from NSUserDefault
    if let myToken = userDefaults.valueForKey("token"){


        // calling method to get the user info
        getUserInfo(myToken as! String)

        // calling method to get the product type
        func getFoodCategory(completionHandler: (NSDictionary?, NSError?) -> ()) {
            getProductTypes(myToken as! String, completionHandler: completionHandler)
        }
        getFoodCategory() { responseObject, error in
            // use responseObject and error here

            let foodTypesJSON = JSON(responseObject!)
            //to get one single food category
            currentFoodType = (foodTypesJSON["types"][0].stringValue)
            print(currentFoodType)


            /////////////////////////////////////////
            func getFoodsByCategory(completionHandler: (NSDictionary?, NSError?) -> ()) {
                print("getting " + currentFoodType)
                self.getProductsByType(myToken as! String, productType: currentFoodType, completionHandler: completionHandler)
            }

            getFoodsByCategory() { responseObject, error in
                // use responseObject and error here
                print("responseObject = \(responseObject); error = \(error)")

                return
            }

           return
        }

    }

然后我从那里调用的另外两个函数是非常直接的 Alamofire 请求,回调到上面的 completionHandlers

    //GET THE PRODUCT TYPES FROM THE SERVER
func getProductTypes(myToken: String, completionHandler: (NSDictionary?, NSError?) -> ())  {

    let requestToken = "Bearer " + myToken
    let headers = ["Authorization": requestToken]
    let getProductTypesEndpoint: String = BASE_URL + PRODUCT_TYPES


    Alamofire.request(.GET, getProductTypesEndpoint, headers: headers)
        .responseJSON{ response in
            switch response.result {
            case .Success(let value):
                completionHandler(value as? NSDictionary, nil)
            case .Failure(let error):
                completionHandler(nil, error)
            }
    }//END ALAMOFIRE GET responseJSON


}

上面的函数returns像"Desserts"这样的单一食物将在下面的函数中使用,从服务器获取所有甜点

//GET THE PRODUCTS FROM THE SERVER GIVEN A CATEGORY
func getProductsByType(myToken: String, productType: String, completionHandler: (NSDictionary?, NSError?) -> ()){

    let requestToken = "Bearer " + myToken
    let headers = ["Authorization": requestToken]
    let getProductTypesEndpoint: String = BASE_URL + PRODUCT_BY_TYPE + productType

    Alamofire.request(.GET, getProductTypesEndpoint, headers: headers)
        .responseJSON { response in
            switch response.result {
            case .Success(let value):
                print("no errors")
                let auth = JSON(value)
                print("The pbt GET description is: " + auth.description)
                completionHandler(value as? NSDictionary, nil)
            case .Failure(let error):
                print("there was an error")

                completionHandler(nil, error)
            }
    }//END ALAMOFIRE GET responseJSON
}

这很好用,因为当我在 getProductsByType 函数中打印时

使用

print("The pbt GET description is: " + auth.description)

我得到了所有产品的 JSON ,但问题出在我嵌套回调的 viewDidload 函数中

getFoodsByCategory() { responseObject, error in
                // use responseObject and error here
                print("responseObject = \(responseObject); error = \(error)")                   
                return
            }

那个位中的打印显示出了点问题,所以我无法按照我的意愿解析我的回复。

因为我得到以下

responseObject = nil; error = nil

所以我猜一定有不同的方法来嵌套这些回调?

看看 PromiseKit 中的链式承诺。这也适用于 Alamofire:

func loadFoo() -> Promise<Bar> {
    return Promise<Bar> { fulfill, reject in 
        Alamofire.request(.GET, "url")
        .responseJSON { response in
            switch response.result {
                case .Success(let value):
                     let bar = Bar(fromJSON: value)
                     fulfill(bar)
                case .Failure(let error):
                     reject(error)
            }
        }
    }
}


// Usage    
getBar()
.then { bar -> Void in
    // do something with bar
}
.error { error in
    // show error
}

这是一个非常简单的示例,但您可以在文档中找到更多相关示例。