选择器视图不更新

时间:2016-08-09 21:34:32

标签: ios json swift

由于一些问题,我正在尝试使用Alamofire,在这里我有一个获取在线JSON文件的Alamofire,获取四个结果,将它们放在选择器视图上,并刷新以便它们可以显示。这里的代码完美无缺:

 Alamofire.request(.GET, "https://example.com/json.json", parameters: ["foo": "bar"])
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value {
                    self.mypickerview.delegate = self
                    self.mypickerview.dataSource = self
                    self.pickerData = [JSON["One"] as! String, JSON["Two"] as! String, JSON["Three"] as! String, JSON["Four"] as! String]

                    self.mypickerview.delegate = self;

                }




        }

但问题是,使用此代码,虽然它设法成功获取数据,但它并未在选择器视图中显示:

// Setup the session to make REST GET call.  Notice the URL is https NOT http!!
let postEndpoint: String = "https://example.com/json.json"
let session = NSURLSession.sharedSession()
let url = NSURL(string: postEndpoint)!

// Make the POST call and handle it in a completion handler
session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
    // Make sure we get an OK response
    guard let realResponse = response as? NSHTTPURLResponse where
        realResponse.statusCode == 200 else {
            print("Not a 200 response")
            return
    }

    // Read the JSON
    do {
        if let ipString = NSString(data:data!, encoding: NSUTF8StringEncoding) {
            // Print what we got from the call
            print(ipString)

            // Parse the JSON to get the data
            let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
            let One = jsonDictionary["One"] as! String
            let Two = jsonDictionary["Two"] as! String
            let Three = jsonDictionary["One"] as! String
            let Four = jsonDictionary["One"] as! String


            self.mypickerview.delegate = self
            self.mypickerview.dataSource = self
            self.pickerData = [One, Two, Three, Four]
            self.mypickerview.delegate = self;



        }
    } catch {
        print("bad things happened")
    }

}).resume()

第二个代码会阻止选择器视图中的选项出现,会出现什么问题?

2 个答案:

答案 0 :(得分:1)

之后
self.pickerData = [One, Two, Three, Four]

调用以下内容强制重新加载主线程中的数据,如@SaintThread在评论中所述

self.mypickerview.reloadAllComponents()

答案 1 :(得分:1)

当您需要更改pickerView时 - 请调用此方法!

self.mypickerview.reloadAllComponents()
相关问题