嵌套Alamofire回调或返回全球使用价值

时间:2016-01-13 01:15:49

标签: swift2 ios9 alamofire swifty-json

我目前正在尝试嵌套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


}

上面的函数会返回一个像“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

所以我的猜测是,必须有一种不同的方法来嵌套这些回调吗?

1 个答案:

答案 0 :(得分:0)

看看来自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
}

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