Why can't I get the request result form Alamofire

淺唱寂寞╮ 提交于 2019-11-29 17:38:58

So asynchronous calls are executed on another thread. Thus, when you call the function populateVenue(), the populateVenue() function is not completing before the println("The 2st result array : \(self.resultArray)" ). If you set up your populateVenue() to have a closure, this won't happen. Example:

override func viewDidLoad() {

   super.viewDidLoad()

   populateVenue( { (error, result) -> Void in 
      println("The 2st result array : \(self.resultArray)" )
   })
}

func populateVenue(completion: (error: NSError?, result: AnyObject?) -> Void) {
    Alamofire.request(.POST, "http://localhost:8080/ws/automobile/global/auction/latest/venues").responseJSON() {
    (_, _, jsonData, error) in

       if error == nil {
          // do whatever you need
          // Note that result is whatever data you retrieved
          completion(nil, result)
       } else {
           println("Errror")
           completion(error!, nil)
       }
   }
}

Edit:

I am still trying to understand your problem, but this is my best shot. Note that I have no idea what the purpose of resultOld is so I removed it. If you absolutely need it you can add it back in. My design here is to make the properties optional, and return the result in the completion block. Then in viewDidLoad, you can initialize the property array and reload your screen.

@IBOutlet var venuePicker : UIPickerView?

// Try making this optional so you can tell when the network call is completed
var result: [String]?

var error = "Error"

let refreshControl = UIRefreshControl()

override func viewDidLoad() {
    if result == nil {
       populateVenues ( { (result) -> Void in
          self.result = result
          self.venuePicker?.reloadAllComponents()
       })
    }
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
     if result != nil {
        return result.count
     } else {
        return 0
     }
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

    return result[row]
}

func populateVenues(completion : (result : [String]?) -> Void){
    Alamofire.request(.POST, "http://localhost:8080/ws/automobile/global/auction/latest/venues").responseJSON() {
        (_, _, jsonData, error) in

        if error == nil{
            var venues = JSON(jsonData!)

            for (k, v) in venues {

                resultOld[k] = v.arrayValue[0].stringValue

            }

            result = resultOld.values.array

            completion(result: result)
        }
        else{
            println("Error!!")
            completion(result: nil)
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!