簡體   English   中英

NSURLSession,完成塊,Swift

[英]NSURLSession, Completion Block, Swift

我正在使用NSURLSession。 我有一個帶有餐廳的數組,我向api中的數組中的每個餐廳索要菜餚。 dataTask工作正常,僅在所有dataTasks完成后才嘗試調用方法確實很困難。

 self.findAllDishesOfRestaurants(self.restaurantsNearMe) { (result) -> Void in
        if result.count != 0 {
              self.updateDataSourceAndReloadTableView(result, term: "protein")
        } else {
            print("not ready yet")
        } 
    }

無論我的完成塊如何,self.updateDataSourceAndREloadTableView都不會被調用。 這是我的findAllDishesOfRestaurants函數

func findAllDishesOfRestaurants(restaurants:NSArray, completion:(result: NSArray) -> Void) {
    let allDishesArray:NSMutableArray = NSMutableArray()
    for restaurant in restaurants as! [Resturant] {
        let currentRestaurant:Resturant? = restaurant
        if currentRestaurant == nil {
            print("restaurant is nil")
        } else {
            self.getDishesByRestaurantName(restaurant, completion: { (result) -> Void in
                                            if let dishesArray:NSArray = result {
                                                restaurant.dishes =  dishesArray
                                                print(restaurant.dishes?.count)
                                                allDishesArray.addObjectsFromArray(dishesArray as [AnyObject])
                                                self.allDishes.addObjectsFromArray(dishesArray as [AnyObject])
                                                print(self.allDishes.count)
                                            }
                                            else {
                                                print("not dishes found")
                                        }
                                          // completion(result:allDishesArray)
                                    })
             completion(result:allDishesArray)
        }
    }
}

這是我執行dataTasks的函數。

 func getDishesByRestaurantName(restaurant:Resturant, completion:(result:NSArray) ->Void) {

    var restaurantNameFormatted = String()
    if let name = restaurant.name {
    for charachter in name.characters {
        var newString = String()
        var sameCharacter:Character!
        if charachter == " " {
           newString = "%20"
            restaurantNameFormatted = restaurantNameFormatted + newString
        } else {
            sameCharacter = charachter
            restaurantNameFormatted.append(sameCharacter)
        }
       // print(restaurantNameFormatted)
    }
}
    var urlString:String!
        //not to myself, when using string with format, we need to igone all  the % marks arent ours to replace with a string, otherwise they will be expecting to be replaced by a value
         urlString = String(format:"https://api.nutritionix.com/v1_1/search/%@?results=0%%3A20&cal_min=0&cal_max=50000&fields=*&appId=XXXXXXXXXappKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXX",restaurantNameFormatted)
    let URL = NSURL(string:urlString)
    let restaurantDishesArray = NSMutableArray()
  let session = NSURLSession.sharedSession()
                let dataTask = session.dataTaskWithURL(URL!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
                do {
                let anyObjectFromResponse:AnyObject = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
                    if let asNSDictionary = anyObjectFromResponse as? NSDictionary {
                        let hitsArray = asNSDictionary.valueForKey("hits") as? [AnyObject]
                                                for newDictionary in hitsArray! as! [NSDictionary]{
                                                    let fieldsDictionary = newDictionary.valueForKey("fields") as? NSDictionary
                                                    let newDish = Dish.init(dictionary:fieldsDictionary!, restaurant: restaurant)
                                                    restaurantDishesArray.addObject(newDish)
                        }
                    }
                    completion(result:restaurantDishesArray)
                } catch let error as NSError {
                    print("failed to connec to api")
                    print(error.localizedDescription)
                }
            }
            dataTask.resume()
}

就像我之前說過的那樣,我需要等到有趣的findAllDishesOfRestaurants完成。 我嘗試編寫完成塊,但不確定執行是否正確。 任何幫助是極大的贊賞。 謝謝

問題是您要在completion任務之前在findAllDishesOfRestaurants中調用completion方法。 實際上,您為列表中的每個餐廳都調用一次,這可能不是您想要的。

我的建議是讓您研究NSOperationQueue的原因有兩個:

  1. 這將使您限制對服務器的並發請求數,因此服務器不會被請求淹沒。
  2. 它使您可以輕松控制何時完成所有操作。

但是,如果您正在尋找快速解決方案,則需要使用GCD組dispatch_group_createdispatch_group_enterdispatch_group_leavedispatch_group_notify ,如下所示。

func findAllDishesOfRestaurants(restaurants:NSArray, completion:(result: NSArray) -> Void) {
    let group = dispatch_group_create() // Create GCD group

    let allDishesArray:NSMutableArray = NSMutableArray()
    for restaurant in restaurants as! [Resturant] {
        let currentRestaurant:Resturant? = restaurant
        if currentRestaurant == nil {
            print("restaurant is nil")
        } else {
            dispatch_group_enter(group) // Enter group for this restaurant
            self.getDishesByRestaurantName(restaurant, completion: { (result) -> Void in
                if let dishesArray:NSArray = result {
                    restaurant.dishes =  dishesArray
                    print(restaurant.dishes?.count)
                    allDishesArray.addObjectsFromArray(dishesArray as [AnyObject])
                    // self.allDishes.addObjectsFromArray(dishesArray as [AnyObject])  <-- do not do this
                    // print(self.allDishes.count)
                }
                else {
                    print("not dishes found")
                }
                // completion(result:allDishesArray)  <-- No need for this, remove
                dispatch_group_leave(group) // Leave group, marking this restaurant as complete
            })
            // completion(result:allDishesArray) <-- Do not call here either
        }
    }

    // Wait for all groups to complete
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        completion(result:allDishesArray)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM