2016-04-14 19 views
-2

残りのWebサービスからJSONオブジェクトを取得するオブジェクトからデータを取得して、それをテーブルビューに表示したいとします。配列は保存されません

class TableViewController1: UITableViewController { 
    var nomProduit = ["ok"] 
    var prixProduit = [""] 
    var vt1 : String? 
    var vt2 : String? 

    var i : Int! 
    var compteur1:Int! 
    var resultat1:NSArray? 
    var x : AnyObject? 


    override func viewDidLoad() { 


     super.viewDidLoad() 
     // \(detectionString) 
     let str:String = "http://vps43623.ovh.net/yamoinscher/api/products/6194005492077" 
     let url = NSURL(string: str)! 

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

      if let urlContent = data { 

       do { 

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) 


        self.resultat1 = jsonResult["meme_categorie"] as? NSArray 

        self.compteur1 = self.resultat1!.count 
        print(self.compteur1!) 
        //self.value = (compteur1 as? Int)! 

        for self.i=0 ; self.i < self.compteur1! ; self.i = self.i+1 { 
        if let aStatus = self.resultat1![self.i] as? NSDictionary{ 
         self.vt1 = aStatus["libelle_prod"]! as? String 
         self.nomProduit.append(self.vt1!) 
         self.vt2 = aStatus["prix"]! as? String 
         self.prixProduit.append(self.vt2!) 
         //print(self.nomProduit[self.i]) 


        } 

        } 


       } catch { 

        print("JSON serialization failed") 

       } 


      } 


     } 

     task.resume() 


    } 

その後、私の問題は、この配列がnilのままということです。ここ

self.prixProduit.append(self.vt2!) 

は私のコードの残りの部分である

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return 17 
} 


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! customCell1 

    // cell.PrixSim.text = nomProduit[indexPath.row] 


    print(self.nomProduit[0]) 



    return cell 
} 
+1

は 'NSURLSession.sharedSession()。dataTaskWithURLは()' 'です。 – Larme

+1

コードをデバッグして、 'print'をどこに挿入して何が起こっているのかを確認すれば、メソッドが非同期に実行されることがわかります。 – luk2302

+0

あなたはApp Transport Security Settingsを許可しましたか? –

答えて

1

まずカテゴリオブジェクトのカスタム構造体を使用し、物事がずっと楽になります。 viewDidLoadTableViewController1

class TableViewController1: UITableViewController { 

宣言この構造体

struct Produit { 
    var id : String 
    var prix : String 
    var title : String 
    } 

とデータ・ソース配列(他のすべてのプロパティ/変数を忘れる)

var produits = [Produit]() 

の開始時に

GETデータ、データソース配列を生成してテーブルをリロードするメインスレッドのビュー
このコードは、アイテムの実際の数ではなく、ハードコードされた数を返すnumberOfRowsInSectionでスウィフトネイティブコレクション型

override func viewDidLoad() { 

    super.viewDidLoad() 
    // \(detectionString) 
    let str = "http://vps43623.ovh.net/yamoinscher/api/products/6194005492077" 
    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 memeCategorie = jsonResult["meme_categorie"] as? [[String:String]] { 
       for categorie in memeCategorie { 
       if let prix = categorie["prix"], title = categorie["libelle_prod"], id = categorie["id"] { 
        self.produits.append(Produit(id: id, prix: prix, title: title)) 
       } 
       } 
       dispatch_async(dispatch_get_main_queue()) { 
       self.tableView.reloadData() 
       } 
      } 
      } 
     } catch { 
      print("JSON serialization failed", error) 
     } 
     } else if let connectionError = error { 
      print("connection error", connectionError) 
     } 
    }  
    task.resume() 
    } 

を使用します。
デフォルト値は1なので、numberOfSectionsInTableViewは省略できます。 cellForRowAtIndexPath

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return produits.count 
    } 

インデックスパスでアイテムを取得し、あなたのラベル(または任意)に値を割り当てます。今のところ、値はちょうど印刷されます。あなたは `UITableVIew`ために` reloadData`が必要asynch`

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! customCell1 

    let produit = produits[indexPath.row] 

    print(produit.id, produit.title, produit.prix) 
    return cell 
    } 

} 
関連する問題