我面临的问题是我无法使用JSON数据填充空数组,并且无法在StackOverflow上找到类似的问题。
在函数本身内,我可以得到空数组并在函数中填充数组。然后在downloadRestaurantDetails函数中调用print函数以查看我已解析的信息。
但我无法填充函数外部的原始空数组,以便我可以获取填充的数组并在不同的函数中使用它。
import UIKit
import GoogleMaps
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
var placeIDArray = [String]()
var placeID: String!
override func viewDidLoad() {
super.viewDidLoad()
downloadRestaurantDetails { () -> () in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadRestaurantDetails(completed: DownloadComplete) {
//url is acquired through a file created for global variables
Alamofire.request(.GET,url).responseJSON { (response) -> Void in
if let value = response.result.value {
let json = JSON(value)
//Acquire All place_id of restaurants
if let results = json["results"].array {
for result in results {
if let allPlace_ID = result["place_id"].string {
//Add All place_id's into an array
self.placeIDArray.append(allPlace_ID)
}
}
}
}
// i call this method to check and see if there is anything placed in the array outside of the downloadRestaurantDetails method.
func check() {
if self.placeIDArray.count > 1 {
print(self.placeIDArray)
} else {
print(self.placeIDArray.count)
}
}
总结一下,我想解决的问题,
答案 0 :(得分:1)
downloadRestaurantDetails
是异步的。因此,如果在调用上述函数后立即调用check
,则可能(并且很可能)尚未获取JSON,因此placeIDArray
尚未填充。你必须在回调中调用它,因为那是在数据实际下载并填充到数组中的时候。
所以:
在设置数据后添加回调:
func downloadRestaurantDetails(completed: DownloadComplete) {
//url is acquired through a file created for global variables
Alamofire.request(.GET,url).responseJSON { (response) -> Void in
if let value = response.result.value {
let json = JSON(value)
//Acquire All place_id of restaurants
if let results = json["results"].array {
for result in results {
if let allPlace_ID = result["place_id"].string {
//Add All place_id's into an array
self.placeIDArray.append(allPlace_ID)
}
}
// !!! Call the callback:
completed()
}
}
然后你可以在回调中调用check
:
override func viewDidLoad() {
super.viewDidLoad()
downloadRestaurantDetails { () -> () in
// The array is now filled.
self.check()
}
}