swift数组只附加3个项而不是5个

时间:2018-01-25 05:26:13

标签: arrays json swift nsmutabledictionary swifty-json

作为标题。我以为我已经开始工作,但它只在我的NSMutableDictionary数组中添加了3个项目。我想也许是因为在完全追加项目之前调用了performsegue?我该如何解决这个问题?

(我也不知道为什么但是当我打印(someDict.count)它给了我17 ...它应该只有5但是因为只有5个企业)

以下是代码:

var searchBusinessDictionary: [NSMutableDictionary] = []

    func retrieveBusinessFromAPI(id: String){
    let url = URL(string: "https://api.yelp.com/v3/businesses/\(id)")
    var request: URLRequest = URLRequest(url: url!)
    request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
        let businessData = JSON(data)
            var someDict = NSMutableDictionary()
            someDict.setValue(businessData["name"], forKey: "Business Name")
            someDict.setValue(businessData["url"], forKey: "Business Yelp URL")
            someDict.setValue(businessData["image_url"], forKey: "Business image URL")
            someDict.setValue(businessData["hours"][0]["is_open_now"], forKey: "Business Is Open Now")
            someDict.setValue(businessData["price"], forKey: "Business Price")
            someDict.setValue(businessData["rating"], forKey: "Business Rating")
            someDict.setValue(businessData["location"]["display_address"], forKey: "Business Location")
        self.searchBusinessDictionary.append(someDict)
        self.performSegue(withIdentifier: "businessListSegue", sender: self)
    })
    task.resume()
}

尝试将我的performsegue调度到我的主线程但是我不认为执行segue被调用,因为我的视图没有改变

以下是代码:

@IBAction func saerch(_ sender: UIButton) {
    self.yelpAPIRequest(completion: {
        OperationQueue.main.addOperation {
            self.performSegue(withIdentifier: "businessListSegue", sender: self)
        }
    })
}

 func yelpAPIRequest(completion: ()->()){
    let coordinate = YLPCoordinate(latitude: self.userLatitude, longitude: self.userLongitude)
    let query = YLPQuery(coordinate: coordinate)
    query.term = "dessert"
    query.limit = 5

    YLPClient.authorize(withAppId: clientId, secret: clientSecret).flatMap { client in
        client.search(withQuery: query)
        }.onSuccess { search in
            if search.businesses.isEmpty == false {
                let topBusiness = search.businesses

                for i in topBusiness{
                    print(i.identifier)
                    self.retrieveBusinessFromAPI(id: i.identifier)
                }

            } else {
                print("No businesses found")
            }
        }.onFailure { error in
            print("Search errored: \(error)")
        }
}

0 个答案:

没有答案