不返回解析的 json,即使它打印了。
guard let unwrappedZipcode = self.zipCode else {print("did not unwrap zipcode"); return}
self.coordinateStore.getUserCoordintes(zipcode: unwrappedZipcode, completion: { (coordinatesJson) in
print("********************")
print(coordinatesJson)
print("does this work")
print("*******************")
print(self.coordinateStore.locationCoordinates.first)
})
这是进行网络调用并解析 JSON 的函数:
func getUserCoordintes (zipcode: String, completion:@escaping ([Coordinates]) -> ()){
GoogleCoordinateAPIClient.getCoordinateInformation(zipCode: zipcode) { (googleAPICoordinatesJson) in
guard let unwrappedJson
= googleAPICoordinatesJson as? [String: Any] else {print("did not unwrap at the first level"); return}
guard let secondLevelArray = unwrappedJson["results"] as? Array<Any> else {print("did not unwrap at the second level"); return}
guard let firstElementFromArray = secondLevelArray[0] as? [String : Any] else {print("did not unwrap at the third level"); return}
guard let geometryDictionary = firstElementFromArray["geometry"] as? [String: Any] else {print("did not unwrap at the fourth level"); return}
guard let locationDictionary = geometryDictionary["location"] as? [String: Any] else {print("did not unwrap at the fifth level"); return}
guard let locationLat = locationDictionary["lat"] as? Double else {print("did not unwrap latitude"); return}
guard let locationLng = locationDictionary["lng"] as? Double else {print("did not unwrap longitude"); return}
let coordinatesObject = Coordinates.init(latitude: locationLat, longitude: locationLng)
self.locationCoordinates.append(coordinatesObject)
print(self.locationCoordinates.count)
print("*********************************")
print(self.locationCoordinates.first?.latitude)
print(self.locationCoordinates.first?.longitude)
print("*********************************")
}
completion(self.locationCoordinates)
}
打印出 1 和坐标,但显示为空数组,其中没有任何内容。
最佳答案
您有一个异步调用。您需要在异步调用的完成 block 内调用函数的完成处理程序。
移动线:
completion(self.locationCoordinates)
就在 print
语句之后。正如您现在所看到的,您对 completion(self.locationCooperatives)
的调用早在异步调用开始之前就已经进行了。
关于arrays - 为什么 JSON 返回这样的值 2.2348142859517371e-314 和 6.9531204333502763e-310,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978369/