2017-06-02 73 views
0

所以我有一個解析一些比特幣價格數據的視圖控制器。該函數成功響應並解析數據,但我似乎無法讓它顯示在tableView中。tableView單元格不顯示數據,有什麼問題? (Swift 3)

我已經通過一個測試單元測試了網點和身份,其中確實是的工作。

我在做什麼錯?

代碼:`

import UIKit 
import Alamofire 
import AlamofireObjectMapper 
import ObjectMapper 

class Response: Mappable{ 
    var data: [Amount]? 

required init?(map: Map){ 

} 
    func mapping(map: Map) { 
    data <- map["data"] 
    } 
} 

class Amount: Mappable { 
    var data : String? 

    required init?(map: Map){ 

} 
    func mapping(map: Map) { 
    data <- map["data.amount"] 
    } 
} 

class ViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource { 
    var mount = [String]() 
    var am = [String]() 



    @IBOutlet var tableView: UITableView! 


func Call_bitcoin() { 
    let url = "https://api.coinbase.com/v2/prices/BTC-USD/buy" 
    Alamofire.request(url).responseObject{ (response: DataResponse<Amount>) in 
     let mount = response.result.value 
     let am = mount?.data 


     self.tableView.reloadData() 

     return 


    } 
} 





    override func viewDidLoad() { 
    super.viewDidLoad() 

    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") 
    tableView.delegate = self 
    tableView.dataSource = self 
    Call_bitcoin() 
} 


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


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    print("You tapped cell number \(indexPath.row).") 
} 


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    print(am) 
    cell.textLabel?.text = am[indexPath.row] 
    return cell 
} 

} 

`

+0

你設置了'tableView.dataSource = self'和'tableView.delegate = self'嗎? – Legonaftik

+0

如果您的單元格不可見可能'am.count'返回0 –

回答

0

你想在你的Call_bitcoin()功能添加元素,但你做錯了。您已經創建了var am = [String]()。所以你不需要使用let am = mount?.data。您可以將數據添加到已創建的am變量中。你需要改變你的一些代碼行中Call_bitcoin()功能:

來源:

let mount = response.result.value 
let am = mount?.data 

要:

let mount = response.result.value 
am.append(mount?.data) // This part should be set by your 'mount?.data' value type 
+0

謝謝!這大多是正確的。 Xcode對我大喊,並把它變成這樣:self.am.append((mount?.data)!) – hisairnessag3

+0

不客氣:) – kkakkurt

0

您的JSON不返回數組,它有dictionary.that爲什麼你

am.count = 0 

首先解決您的數據並將數據放入數組中。

{"data":{"amount":"2414.88","currency":"USD"},"warnings":[{"id":"missing_version","message":"Please supply API version (YYYY-MM-DD) as CB-VERSION header","url":"https://developers.coinbase.com/api#versioning"}]}