我一直在试图找出为什么我的JSON数据没有被附加到我的全局变量中。我知道这是因为我的函数需要时间来获取和处理JSON数据。所以我尝试使用完成块检查是否有任何内容。但是,我内心仍然没有任何东西。我想知道我在做什么呢?
以下是代码:
@IBAction func dismissButton(_ sender: UIButton) {
yelpAPIRequest(completion: {
print("WE are done")
print(self.businessName)
})
}
func yelpAPIRequest(completion:@escaping ()->()){
let coordinate = YLPCoordinate(latitude: userLatitude , longitude: userLongitude)
let query = YLPQuery(coordinate: coordinate)
query.term = "dessert"
query.limit = 5
query.radiusFilter = 16094
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)
}
completion()
} else {
print("No businesses found")
}
}.onFailure { error in
print("Search errored: \(error)")
}
}
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)
self.businessName.append(businessData["name"].string)
self.businessYelpURL.append(businessData["url"].string)
self.businessImageURL.append(businessData["image_url"].string)
self.businessIsOpenNow.append(businessData["hours"][0]["is_open_now"].bool)
self.businessPrice.append(businessData["price"].string)
self.businessRating.append(businessData["rating"].int)
self.businessAddress.append([businessData["location"]["display_address"].string])
})
task.resume()
}
编辑:是的,我看过其他关于同一主题的帖子,但是他们的makority都指向完成:我已经完成了但我的数据仍未保存