2017-05-19 8 views
1

これはなぜ機能していないのですか?私はMYSQLデータベースから名前とタイトルを抽出するWebサービスを持っています。その働き。 JSONの結果とhtml形式の文字列の両方をテストするprint文を追加しました。何らかの理由で、私がラベルに書き出すときには何も表示されません。どんな助けでも感謝します。以下は完全なコードです。Webサービスの値がラベルに表示されない

import UIKit 

class ContactsViewController: UIViewController { 

    @IBOutlet weak var contactsLabel: UILabel! 
    //Our web service url 
    let URL_GET_TEAMS:String = "http://www.example.com/apps/getcontacts.php" 

    var myLabel : String = "" 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 


     //created NSURL 
     let requestURL = NSURL(string: URL_GET_TEAMS) 


     //creating NSMutableURLRequest 
     let request = NSMutableURLRequest(url: requestURL! as URL) 

     //setting the method to post 
     request.httpMethod = "GET" 

     //creating a task to send the post request 
     let task = URLSession.shared.dataTask(with: request as URLRequest){ 
      data, response, error in 

      //exiting if there is some error 
      if error != nil{ 
       print("error is \(error)") 
       return; 
      } 

      //parsing the response 
      do { 
       //converting resonse to NSDictionary 
       var teamJSON: NSDictionary! 
       teamJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 

       //getting the JSON array teams from the response 
       let teams: NSArray = teamJSON["contacts"] as! NSArray 

       //looping through all the json objects in the array teams 
       for i in 0 ..< teams.count{ 

        //getting the data at each index 
        let teamId:String = (teams[i] as! NSDictionary)["title"] as! String! 
        let teamName:String = (teams[i] as! NSDictionary) ["name"] as! String! 



        //displaying the data 
        print("id -> ", teamId) 
        print("name -> ", teamName) 
        print("===================") 
        print("") 
        self.myLabel = self.myLabel + "<font size='5'><b>" + teamId + "</font>:</b> " + "<font size='5'>" + teamName + "</font><br /><br />" 
        print(self.myLabel) 
       } 

      } catch { 
       print(error) 
      } 
     } 
     //executing the task 
     task.resume() 

     let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) 
     contactsLabel.attributedText = attrStr 
     contactsLabel.sizeToFit() 
    } 

} 
+0

teamIdとteamNameを印刷するときにデータがありますか? – mat

+0

teamIdとteamNameでデータを取得している場合は、self.myLabel = self.myLabel + "" + teamId + "" + " 「+ TEAMNAME +」
DispatchQueue.main.asyncとしてメインスレッドで
「コード{ ...ここにあなたのラベルコード.. } –

+0

私はteamidとTEAMNAME –

答えて

1

あなたが閉鎖のメインスレッドに戻って行かなければならないので、非同期でバックグラウンドスレッドで実行されますURLSession

import UIKit 

class ContactsViewController: UIViewController { 

    @IBOutlet weak var contactsLabel: UILabel! 
    //Our web service url 
    let URL_GET_TEAMS:String = "http://www.example.com/apps/getcontacts.php" 

    var myLabel : String = "" 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 


     //created NSURL 
     let requestURL = NSURL(string: URL_GET_TEAMS) 


     //creating NSMutableURLRequest 
     let request = NSMutableURLRequest(url: requestURL! as URL) 

     //setting the method to post 
     request.httpMethod = "GET" 

     //creating a task to send the post request 
     let task = URLSession.shared.dataTask(with: request as URLRequest){ 
      data, response, error in 

      //exiting if there is some error 
      if error != nil{ 
       print("error is \(error)") 
       return; 
      } 

      //parsing the response 
      do { 
       //converting resonse to NSDictionary 
       var teamJSON: NSDictionary! 
       teamJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 

       //getting the JSON array teams from the response 
       let teams: NSArray = teamJSON["contacts"] as! NSArray 

       //looping through all the json objects in the array teams 
       for i in 0 ..< teams.count{ 

        //getting the data at each index 
        let teamId:String = (teams[i] as! NSDictionary)["title"] as! String! 
        let teamName:String = (teams[i] as! NSDictionary) ["name"] as! String! 



        //displaying the data 
        print("id -> ", teamId) 
        print("name -> ", teamName) 
        print("===================") 
        print("") 
        self.myLabel = self.myLabel + "<font size='5'><b>" + teamId + "</font>:</b> " + "<font size='5'>" + teamName + "</font><br /><br />" 
        print(self.myLabel) 
       } 

      } catch { 
       print(error) 
      } 

      DispatchQueue.main.async { 
       let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) 
       contactsLabel.attributedText = attrStr 
       contactsLabel.sizeToFit() 
      } 
     } 
     //executing the task 
     task.resume() 
    } 

} 

あなたがresume()を呼び出すと、タスクはバックグラウンドで実行されますので、テキストはまだ変わっていない一方、ラベルがすぐに更新されます。これは一般的ですが混乱するエラーです。dataTaskはバックグラウンドスレッドで実行されるため、そのClousure内のUIは更新されます。

+0

私は今日何か新しいことを学んだ。私はdispatchQueueが何をしているかを完全に理解しているかどうかはわかりませんが、私はそのドキュメントを読んでより良い理解を得るでしょう。助けてくれてありがとう。 –

+0

私が気付いたことが少し奇妙なことがあります。私がアプリを起動するとき、すぐに連絡先をタップすると何もロードされません。もし私が戻ってきたら再びデータが入ってきます。私はブラウザからWebサービスを直接呼び出すときにその遅延が見られることはありません。私はそれがアプリケーションのフロントエンドにコードを移動し、必要に応じてそれを連絡先のビューに渡す方が良いのだろうかと思っています。 –

関連する問題