2017-04-11 5 views
0

現在、質問と回答の配列を持つWebサービスリンクがあります。私はこれらの答えをロードするために私のpickerviewが必要ですが、これはすべてまたは任意のデータで配列をロードしていません。配列の名前は、あなたがJSONレスポンスを受信した後、ピッカービューをリロードする必要があるとして、ピッカービューが空である「解答」Webサービスから配列をピッカービューに取得

class QuestionsViewController: UIViewController, UIPickerViewDelegate { 

@IBOutlet weak var usernamelabel: UILabel! //sets username label 
@IBOutlet weak var Next: UIButton! //next button 
@IBOutlet weak var itemLabel: UILabel! //item user has selected 
@IBOutlet weak var Question: UILabel! //sets question label 
@IBOutlet weak var pickerview: UIPickerView! //sets picker view 

public var totalQuestions: Int = 0 //sets total question to 0 
public var currentQuestion = 0 //sets current question to 0 
public var totalCorrect: Int = 0 //sets totalcorrect to 0 
var itemSelected: String = "" //item selected 
var LabelText = String() 
//let Exam = QuestionList() //uses the questions class for instances 
//var Questions = QuestionList.getDummyQuestions() 
@IBOutlet weak var share: UIButton! 


//var listQuestions = [[String: AnyObject]]() 

var listQuestions = [[String: AnyObject]]() 
var titles: [String] = [] 



var quiz = QuestionList() 

var ref: FIRDatabaseReference! 
var refHandle: UInt! 


override func viewDidLoad() { 


    super.viewDidLoad() //when the app is loaded 
    //authPlayer() 

    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]] 

       //self.tableview.reloadData() 

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


    share.isHidden = true 

    ref = FIRDatabase.database().reference() //reference 
    refHandle = ref.child("Questions").observe(.value, with: { (snapshot)in 
     let dataDict = snapshot.value as! [String: AnyObject] 
     print (dataDict) 
    }) 
    usernamelabel.text = LabelText //username 

    pickerview.delegate = self 

    itemLabel.text = "" //loads the item label of whats selected 
    totalQuestions = QuestionList.getDummyQuestions().count 
    itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[currentQuestion] //initially when loaded first item is selected 
    itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[1] 
    //Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest 
    //Question.text = Exam.quiz[currentQuestion][0] //first element in first row of array 
    Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest 
    //cell.EventImgView.image = event["Image"] as? UIImage 

    //Question.text = q["Title"] as? String 




} 


func numberOfComponents(in pickerView: UIPickerView) -> Int { 

    return 1 //return one component from the picker 
} 

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ 
    //return QuestionList.getDummyQuestions()[currentQuestion].answers.count 
    //let q = listQuestions[row] 
    //return listQuestions[currentQuestion].count[row] 
    //return listQuestions.count[row] 
    return listQuestions.count 
} 

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


    //return QuestionList.getDummyQuestions()[currentQuestion].answers[row] 
    let q = listQuestions[row] 
    return q["Answers"] as? String 

    //cell.EventImgView.image = event["Image"] as? UIImage 

} 

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

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

} 

@IBAction func btnShareClicked(_ sender: UIButton) { 

    if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) { 

     let fbShare:SLComposeViewController = SLComposeViewController(forServiceType:SLServiceTypeFacebook) 
     //fbShare.setInitialText("You Scored on the IT Quiz:" + itemLabel.text!) 
     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) 

    } 

} 

func addGC(_ sender: Any) { 


} 

/*func authPlayer() { 
    let localPlayer = GKLocalPlayer.localPlayer() 
    localPlayer.authenticateHandler = { 
     (view, error) in 

     if view != nil { 
      self.present(view!, animated:true, completion: nil) 
     } 
     else { 
      print(GKLocalPlayer.localPlayer().isAuthenticated) 
     } 
    } 

} 

func saveHighScore(score: String) { 
    if GKLocalPlayer.localPlayer().isAuthenticated { 

    } 
}*/ 





@IBAction func NextAction(_ sender: Any){ 


    if (QuestionList.getDummyQuestions()[currentQuestion].isCorrectQuestion(itemSelected: itemSelected)) { 
     totalCorrect += 1 
     itemLabel.text = String(totalCorrect) + "/" + String(totalQuestions) 
    } 

    if(currentQuestion < totalQuestions - 1) { 
     pickerview.reloadAllComponents() 
     itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[1] 
     Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest 
     currentQuestion = currentQuestion + 1 //moves onto next question and increments 


    } else { 
     pickerview.isHidden = true 
     Question.text = "You have finished" 
     Next.isHidden = true 
     share.isHidden = false; 
    } 

} 

}

答えて

0

と呼ばれています。したがって、この行の後

self.listQuestions = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String:AnyObject]] 

はあなたのJSONので、あなたは何も表示されない理由がある------

self.pickerview.reloadAllComponents() 

------- EDITに

を追加します。解析が間違っています。 JSONはAnswers、Questions &_idを返します。あなたのlistQuestionsはこれらの3つの要素になるでしょう。あなたがする必要があるのは、答えの配列を抽出することです。

として今、あなたのやって

let q = listQuestions[row] 
return q["Answers"] as? String 

qは要素の配列[0]、要素の文字列[1]と要素用の辞書になります[2]

--- EDIT ---- 私が言ったように、2番目の問題は、タイトルが表示されないようにJSONを正しいフォーマットにパースしていないことです。 すでにタイトルの配列がそうすると、明らかに

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

&

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

これはまだコンポーネントをロードしていないにあなたのピッカービューのデリゲートメソッドを更新し、この

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]] for elements in self.listQuestions { for object in elements { if object.key == "Answers" { if let answers = object.value as? [String] { self.titles = answers } } } } self.pickerview.reloadAllComponents() }catch let error as NSError{ print(error) } } }).resume() 

にコードを変更すると宣言しましたピッカービュー内で? – Jonathon

+0

さて、そうです。しかしあなたのコードは間違っています。説明するために私の答えを編集させてください – Devster101

+0

説明のためにありがとう、どうして私のコードの中で答えの配列要素を得るのですか?ありがとう – Jonathon

関連する問題