Swift 数组不会填充 JSON 数据

Swift Array will not populate with JSON Data

我面临的问题是我无法用 JSON 数据填充空数组,并且找不到 Whosebug 上提出的类似问题。

在函数本身中,我可以获得空数组并在函数中填充数组。然后在 downloadRestaurantDetails 函数中调用打印函数以查看我已解析的信息。

但是我无法填充函数外部的原始空数组,因此我无法获取填充的数组并将其用于不同的函数。

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)
    }
}

总而言之,我想解决的问题是,

downloadRestaurantDetails 是异步的。因此,如果您在调用上述函数后立即调用 check,则可能(并且很可能)尚未获取 JSON,因此尚未填充 placeIDArray。你必须在回调中调用它,因为那是数据真正下载并填充到数组中的时候。

所以:

  1. 设置数据后添加回调:

    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()
                }
    }
    
  2. 然后你可以在回调里面调用check

    override func viewDidLoad() {
        super.viewDidLoad()
    
        downloadRestaurantDetails { () -> () in
            // The array is now filled.
            self.check()
        }
    }