选择器视图不加载项目

时间:2017-04-13 03:11:10

标签: ios swift uipickerview mlab

我目前在使用pickerview时遇到问题,因为当我点击app上的测验时,拾取器视图根本没有从Web服务加载。选择器视图应显示Web服务的答案数组。选择器视图是空的任何想法?另外问题是不是从Web服务加载文本标签?

conn = ActionCable.server.connections.first { |c| c.current_user == user_id }
MsgsChannel.new(conn, "made up id").stream_from "your_stream_name"

2 个答案:

答案 0 :(得分:2)

您的ViewController缺少UIPickerViewDataSource协议:

class QuestionsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {}

确保将pickerView的delegatedatasource设置为当前viewController

override func viewDidLoad() {
    super.viewDidLoad() //when the app is loaded

    pickerview.delegate = self
    pickerview.dataSource = self
}

dataTask是异步任务,您应该更新主线程上的UI。

DispatchQueue.main.async {
    self.pickerview.reloadAllComponents()
}

最终的代码应该是这样的:

class QuestionsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var usernamelabel: UILabel!
    @IBOutlet weak var itemlabel: UILabel!
    @IBOutlet weak var Question: UILabel!
    @IBOutlet weak var pickerview: UIPickerView!

    public var totalQuestions: Int = 0
    public var currentQuestion = 0
    public var totalCorrect: Int = 0
    var itemSelected: String = ""
    @IBOutlet weak var share: UIButton!
    var LabelText = String()


    var listQuestions = [[String: Any]]()
    var titles: [String] = []
    var qnames: String = ""

    @IBOutlet weak var Next: UIButton!
    var quiz = QuestionList()

    override func viewDidLoad() {
        super.viewDidLoad() // when the app is loaded

        pickerview.delegate = self
        pickerview.dataSource = self

        let url:String = "https://api.mlab.com/api/1/databases/quiz/collections/question?apiKey=NT28RNl6jX3Ys0x5GJZ6mMSRQEcb_6KA"

        let urlRequest = URL(string: url)

        URLSession.shared.dataTask(with: urlRequest!, completionHandler: {
            (data, response, error) in
            if(error != nil){
                print(error.debugDescription)
            }
            else{
                do{
                    self.listQuestions = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String:AnyObject]]
                    print(self.listQuestions)

                    for elements in self.listQuestions {
                        for object in elements {
                            if object.key == "Answers" {
                                if let answers = object.value as? [String] {
                                    self.titles = answers
                                }
                            }
                            if object.key == "Questions" {
                                if let questions = object.value as? String {
                                    self.qnames = questions
                                }
                            }
                        }
                    }

                    DispatchQueue.main.async {
                        self.pickerview.reloadAllComponents()
                        self.Question.text = self.qnames
                    }

                }catch let error as NSError{
                    print(error)
                }
            }
        }).resume()
    }


    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1 //return one component from the picker
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return titles.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) ->String? {
        return self.titles[row]
    }

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

        itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[row]

    }

    @IBAction func btnShareClicked(_ sender: Any) {
        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {

            let fbShare:SLComposeViewController = SLComposeViewController(forServiceType:SLServiceTypeFacebook)
            fbShare.setInitialText("You Scored " + itemlabel.text! + " on the IT Quiz")
            self.present(fbShare, animated:true, completion:nil)

        } else {
            let alert = UIAlertController(title: "Account", message: "Please login to Facebook",
                                          preferredStyle: UIAlertControllerStyle.alert)

            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil))
            self.present(alert, animated: true, completion: nil)

        }
    }
}

答案 1 :(得分:0)

获得问题标签:

for object in elements {

      if let result = object["Questions"] as? [String: AnyObject] {

           print(result)

}