[swift]为什么不能让请求结果窗体 Alamofire

标签: json Alamofire Swift
发布时间: 2017/3/4 22:13:53
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

Alamofire 请求的结果不去所以,我创建一个数组,它收到了 json 异步调用的输出。从调度 {...} resultArray 不去当我添加 println 来调试代码。第二个出现在第一个之前第一次。 我想要的所有 resultArray Alamofire UIPickerView.Please Help 中显示从获取数据!!!

这里是我的代码

import UIKit
import Alamofire

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{

@IBOutlet var venuePicker : UIPickerView?

var resultOld = [String:String]() // i need it to get only value from json

var result : [String]?

let refreshControl = UIRefreshControl()

override func viewDidLoad() {

    if result == nil {
        populateVenues ({ (error, result) -> Void in
            self.result = result as? [String]
            self.venuePicker?.reloadAllComponents()
        })
    }
}

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

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if result != nil{
        return result!.count// Why i can't use result?.count instead of result!.count
    }
    else{
        return 0
    }
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    if result != nil{
        println(result)
        return result?[row]
    }
    else{
        return "..."
    }
}

func populateVenues(completion : (error: NSError?,result : AnyObject?) -> Void){
    Alamofire.request(.POST, "http://xxxx.xxxx.xxx").responseJSON() {
        (_, _, jsonData, error) in

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

            for (k, v) in venues {

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

            self.result = self.resultOld.values.array

            completion(error: nil,result: self.result)
        }
        else{
            println("Error!!")
            completion(error: error!,result: nil)
        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

这里是我的输出在控制台

The 2st result array : []
The 1st result array : [ORIX Kobe Nyusatsu, NPS Sendai Nyusatsu, JU Gunma, KAA Kyoto, JU Ibaraki, USS Gunma, ISUZU Kobe, NAA Osaka Nyusatsu, SMAP Sapporo Nyusatsu, L-Up PKobeNyusatsu, ARAI Sendai, TAA Minami Kyushu, NPS Oyama Nyusatsu, CAA Tokyo, JU Toyama, USS Shikoku, NPS Gifu Nyusatsu, NAA Fukuoka, KCAA Yamaguchi, JU Fukuoka, LAA Kansai, JAA, TAA Kinki, USS Sapporo, JU Miyagi, USS Fukuoka, JU Tokyo]

拜托,我真的需要去知道我发生了什么,为什么不能买到异步调用的结果第一次。

解决方法 1:

因此,异步调用在另一个线程上执行。因此,当您调用函数 populateVenue()populateVenue() 函数未完成前 println("The 2st result array : \(self.resultArray)" ) 。如果你设置了你 populateVenue() 有一个闭包,这不会发生。 示例︰

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

编辑︰

我仍然试着理解你的问题,但这是我最好的机会。请注意,也不知道 resultOld 的目的是什么,所以我将其删除。如果你绝对需要它你可以添加它回来。我在这里的设计是要使属性可选的并在完成块中返回结果。然后在 viewDidLoad,你可以初始化的属性数组并重新加载您的屏幕。

@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)
        }
    }
}
赞助商