swift 中具有多个 closures/API 请求的函数中的异步完成处理

Asynchronous completion handling in a function with multiple closures/API requests in swift

我刚开始在 Swift 开发,所以我对闭包完全陌生。我也是新手如何处理异步 API 请求。

我已经阅读了很多类似的问题,例如 How to get data to return from NSURLSessionDataTask in Swift and How to use completionHandler Closure with return in Swift?。这些对我有帮助,但我的问题有点不同。

在我的函数中,我想先发出一个 API 请求来获取 JSON 负载。有了这个 JSON 有效载荷中的一些数据,我想发出多个其他 API 请求。在这种情况下,我将为每个 API 请求接收一个 JSON 有效载荷,我想在其中将一些数据存储在我自己的 JSON 数据结构中。

问题是,对于我发出的每个多个 API 请求,我只能 return 我自己的一部分 JSON 数据在我的 CompletionHandler - 这是唯一的方法 return 据我所知,使用闭包发出 API 请求时的数据。

因此,在调用我的函数时,我不想获得多个完成处理程序,而是只想接收一个。

问题是我不知道如何完成处理一个函数中的多个闭包,在本例中是两个闭包。

我已经在下面发布了我的代码 - 我知道它很长而且可能不是那么干净。 然而,要点是,当我更新我的 storeDict 报价时,这将是空的,因为报价字典数组是从第二个闭包内部获取信息的。这显示在函数的底部。

   func getOffersFromWishList(offerWishList: [String], latitude: Double, longitude: Double, radius: Int, completionHandler: ([NSDictionary] -> Void)) {

        var master: [NSDictionary] = []

        var nearby_params: NSDictionary = ["r_lat": latitude, "r_lng": longitude, "r_radius": radius]
        //println(nearby_params)
        var store_id_list: [String] = []


        // Get all store_ids for store which are nearby (Radius determines how nearby)
        singleton_eta.api("/v2/stores", type: ETARequestTypeGET, parameters: nearby_params, useCache: true, completion: { (response, error, fromCache) -> Void in

            if error == nil {

                let json = JSON(response)
                storeArray = json.arrayValue
                //println(storeArray)

                for store in storeArray {

                    var storeDict = [String: AnyObject]()
                    var metaData = [String: String]()
                    var offers: [NSDictionary] = []

                    let name = store["branding"]["name"].stringValue
                    let store_id = store["id"].stringValue
                    let street = store["street"].stringValue
                    let city = store["city"].stringValue
                    let zip_code = store["zip_code"].stringValue
                    let dealer_id = store["dealer_id"].stringValue
                    let logo = store["branding"]["logo"].stringValue

                    metaData = ["name": name, "store_id": store_id, "street": street, "city": city, "zip_code": zip_code, "dealer_id": dealer_id, "logo": logo]

                    store_id_list.append(store_id)

                    //println("Butiks ID: \(store_id)")

                    var offset = 0
                    let limit = 100

                    // Loop through the offers for the specific store id - only possible to request 100 offers each time
                    // A while loop would be more suitable, but I dont know when to stop, as the length of the offerArray can not be counted as it is cant be accessed outside of the closure.
                    for x in 1...2 {

                        var store_params: NSDictionary = ["store_ids:": store_id, "limit": limit, "offset": offset]
                        println(store_params)
                        // Get offers for a specific store_id
                        singleton_eta.api("/v2/offers", type: ETARequestTypeGET, parameters: store_params, useCache: true, completion: { (response, error, fromCache) -> Void in

                            if error == nil {

                                offerArray = JSON(response).arrayValue
                                //println( "TypeName0 = \(_stdlib_getTypeName(offerArray))")

                                //Loop through the recieved offers
                                for of in offerArray {

                                    let name = of["branding"]["name"].stringValue
                                    let dealer_id = of["dealer_id"].stringValue
                                    let heading = of["heading"].stringValue
                                    let description = of["description"].stringValue
                                    let price = of["pricing"]["price"].stringValue
                                    let image = of["images"]["view"].stringValue


                                    //println(heading)

                                    // Loop through our offerWishList
                                    for owl in offerWishList {

                                        let headingContainsWish = (heading.lowercaseString as NSString).containsString(owl.lowercaseString)

                                        // Check if offer match with our wish list
                                        if(headingContainsWish) {

                                            // Save neccesary meta data about each offer to a tuple array
                                            var offer = Dictionary<String, String>()
                                            offer = ["name": name, "dealer_id": dealer_id, "heading": heading, "description": description, "price": price, "image": image, "offerWishItem": owl]

                                            offers.append(offer)


                                        }

                                    }

                                }


                            }

                        })
                        //println(storeDict)
                        offset = offset + limit + 1

                    }

                    storeDict.updateValue(metaData, forKey: "meta_data")
                    storeDict.updateValue(offers, forKey: "offers")  // offers is empty due to its appending inside the closure
                    master.append(storeDict)

                }
             completionHandler(master)

            }

            else {
                println(error)
            }


        })

    }

调用上面的函数

getOffersFromWishList(offerWishList, latitude, longitude, radius) { (master) -> Void in
       println(master)
    }

这是master调用函数时会打印的内容,offers为空

{
"meta_data" =     {
    city = "Kongens Lyngby";
    "dealer_id" = d8adog;
    logo = "https://d3ikkoqs9ddhdl.cloudfront.net/img/logo/default/d8adog_3qvn3g8xp.png";
    name = "d\U00f8gnNetto";
    "store_id" = d2283Zm;
    street = "Kollegiebakken 7";
    "zip_code" = 2800;
};
offers =     (
);
}
{ 
  ...
}

所以我的问题是,return 数据从函数内的第二个闭包到第一个闭包的正确方法是什么?还是我以完全错误的方式这样做? 问题是,我需要一个表视图的所有这些数据,因此一次需要所有数据。

几个想法:

  1. 如果有任何可能在对服务器的单个请求中返回所有这些,那可能会提供更好的性能。通常,与网络延迟相比,在服务器上执行请求所需的时间是无关紧要的。如果您可以避免需要发出一个请求,获得响应,然后发出更多请求,那将是理想的。

    或者你提前请求一定距离内的位置,缓存起来,然后"show me deals for nearby locations"可能不需要这两组请求。

    (我知道这些可能都不适合你,但如果可以的话,你可以考虑一下。如果你可以消除连续请求并专注于大部分并发请求,你将获得更好的性能。)

  2. 让我们暂时假设以上不是一个选项,并且您遇到了一个获取附近位置的请求和另一个获取交易的请求。那么你有几个选择:

    • 您绝对可以通过一次回调沿着您正在考虑的道路前进。例如,您可以发出所有请求,在启动每个请求之前执行 dispatch_group_enter,在每个请求完成后执行 dispatch_group_leave,然后发出 dispatch_group_notify当每个 enter 调用被相应的 leave 调用抵消时调用。因此,在每个请求完成时构建您的响应对象,并且仅当它们完成时,才调用完成闭包。

    • 另一种方法是使用一个行为更像枚举闭包的闭包,在每个站点的交易进入时调用该闭包。这样,UI 可以更新为事情进来,而不是等待一切。如果您的网络速度较慢,则在数据传入时更新 UI 可能更容易接受。 (例如,考虑十个请求,每个请求在慢速 3G 蜂窝连接上需要 1 秒完成:看着它们每秒弹出一个比十秒什么都看不到要容易得多)。

    • 话虽如此,您可能想要完全放弃闭包。您可以考虑 delegate-protocol 模式,在其中为请求指定 delegate,然后为从服务器获得的每个响应实施 protocol 方法。这样您就可以在收到新回复时更新 UI,而不是将所有内容都保留到最后一个回复为止。但是我们认识到有非常不同类型的回复(一种是网站列表,另一个是给定站点的列表交易,第三个是 "I'm all done" and/or“出现错误”,因此当它开始变得如此复杂时,最好为这个接口,并以这种方式处理它。