我正在尝试学习 Swift,并且我有一个使用 Google 的 Places API 的小项目。
我有一个获取地点详细信息的方法,它使用 URLSession 快速发送请求:
func fetchRestaurantDetails(placeId: String) -> Void {
let jsonURLString = "https://maps.googleapis.com/maps/api/place/details/json?placeid=\(placeId)&key=[MY API KEY]"
guard let url = URL(string: jsonURLString) else { return}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
_ = session.dataTask(with: urlRequest) { (data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
let place = try JSONDecoder().decode(Result.self, from: responseData) // New in Swift 4, used to serialize json.
self.rest = place.result
} catch {
print("error trying to convert data to JSON")
return
}
}.resume()
}
我使用这个方法创建了一个餐厅类型的实例,稍后我将把它添加到一个列表中:
func createRestaurant(placeId: String) -> Restaurants {
self.fetchRestaurantDetails(placeId: placeId)
let rest = Restaurants(name: self.rest.name,
formatted_address: self.rest.formatted_address,
website: self.rest.website,
location: ((self.rest.geometry.location.lat,self.rest.geometry.location.lng)),
opening_hours: self.rest.opening_hours.weekday_text,
photo: restImg)
return rest!
}
但是每当我回到“ let rest = Restaurants(...) ”时,所有的值都是零。当我尝试调试它时,它只是跳过我的“ _ = session ”部分一直到resume(),然后再次回到 session 并在resume()结束。没有产生数据。我很困惑,因为我之前成功执行了这段代码,现在我想知道我是否遗漏了什么。谢谢 :-)