从Rest WebService获取PickerData数据

时间:2016-04-18 14:26:15

标签: arrays json swift web-services uipickerview

我从Web服务获取数据,当我想在Json Parsing集团之外使用它时,我的pickerData数组不会保存值。 这是我的代码

var pickerData: [String] = [String]()
var mag : String!
override func viewDidLoad() {
    super.viewDidLoad()
    NomMAG.alpha = 0








        // \(detectionString)
        let str = "http://vps43623.ovh.net/yamoinscher/api/getAllMag"
        let url = NSURL(string: str)!

        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

            if let urlContent = data {

                do {
                    let jsonObject = try NSJSONSerialization.JSONObjectWithData(urlContent, options: [])
                    if let jsonResult = jsonObject as? [String:AnyObject] {
                        if let Pick = jsonResult["magasin"] as? [[String:String]] {
                            for categorie in Pick  {
                               self.mag = categorie["libelle"]!
                                    self.pickerData.append(magasin)

                                    //self.pickerData = [(self.produits[0].magasin)]


                            }
                            print(self.pickerData)
                            dispatch_async(dispatch_get_main_queue()) {
                                self.picker1.reloadInputViews()
                               // print(self.produits.count)
                            }
                        }
                    }
                } catch {
                    print("JSON serialization failed", error)
                }
            } else if let connectionError = error {
                print("connection error", connectionError)
            }

        }      
        task.resume()


    //print(produits.count)
    //pickerData = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "autre"]
    //print(self.pickerData)
    self.picker1.delegate = self

    self.picker1.dataSource = self


    // Do any additional setup after loading the view.
}


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

// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.pickerData.count
}

// The data to return for the row and component (column) that's being passed in


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

    return self.pickerData[row]
}


func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {



    if pickerData[row] == "autre"
    {
        //print(row)

        NomMAG.alpha = 1
    }
    else
    {
        //print(row.description)
        NomMAG.alpha = 0
    }



}

我想让我的PickerView充满我从JsonParsing获得的数据,而PickerData数组在Json的代码块之外是空的

1 个答案:

答案 0 :(得分:0)

在Interface Builder中连接选择器视图的delegatedataSource,并将viewDidLoad替换为

  var pickerData = [String]()

  override func viewDidLoad() {
    super.viewDidLoad()

    let str = "http://vps43623.ovh.net/yamoinscher/api/getAllMag"
    let url = NSURL(string: str)!

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
      if let urlContent = data {
        do {
          let jsonObject = try NSJSONSerialization.JSONObjectWithData(urlContent, options: [])
          if let jsonResult = jsonObject as? [String:AnyObject],
            magasin = jsonResult["magasin"] as? [[String:String]] {
            // filter valid items, map them to an array and filter empty strings
            self.pickerData = magasin.filter { $0["libelle"] != nil }.map { $0["libelle"]! }.filter { !$0.isEmpty}
          }
          dispatch_async(dispatch_get_main_queue()) {
            self.picker1.reloadAllComponents()
          }
        } catch {
          print("JSON serialization failed", error)
        }
      } else if let connectionError = error {
        print("connection error", connectionError)
      }

    }
    task.resume()
  }

您必须添加NomMAG