如何从模型中获取值到控制器

时间:2016-04-15 14:21:45

标签: swift api model-view-controller alamofire

这是我的第一个使用MVC设计模式的程序,我一直坚持如何将模型中的值传递给我的控制器并在我的视图中显示它。我会告诉你我做了什么。请告诉我我做错了什么?或者告诉我如何以其他方式完成它。

模型

class songData: NSObject {

var artistName: String
var albumName: String

init(artistName: String, albumName: String) {
    self.artistName = artistName
    self.albumName = albumName
}

}

控制器

  @IBAction func doTheSearch(sender: AnyObject) {

    itunesAPI().itunesSearch({(song : songData) in


    })

    self.tableView.reloadData()

}

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

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

      var artistAndAlbum = itunesAPI().array[indexPath.row]

    cell.textLabel?.text =
    cell.detailTextLabel?.text =

    return cell

 }

API

  func itunesSearch(completionHandler:(songData)->()) {

    Alamofire.request(.GET, "http://itunes.apple.com/search?", parameters: ["term" : "tamil new songs", "media" : "music"])

        .responseJSON { (response) in

            let json = JSON(response.result.value!)



            if let jsonData = json["results"].arrayObject {
                self.array = jsonData as! [[String : AnyObject]]


            if self.array.count > 0 {
//                    self.array = jsonData as! [[String : AnyObject]]
//                    if let resultsDict = resultsArray.first {


                let albumName = json["results"]["collectionName"].stringValue
                let artistName = json["results"]["artistName"].stringValue


                let song = songData(artistName: artistName, albumName: albumName)

                completionHandler(song)


        }

      }

除了故事板以外,我的视图中没有任何东西,其中包含一个带有单个单元格的表视图。我需要从API获取响应并在视图中显示它。

1 个答案:

答案 0 :(得分:0)

首先,您将要在返回数据后重新加载表。将您的IBAction更新为:

itunesAPI().itunesSearch({(song : songData) in
   self.tableView.reloadData()
})

否则在返回数据之前将调用reloadData。在viewController上设置属性以容纳数据。此外,最好使用大写字母开始一个类名。

var tableData:[SongData] = [SongData]()

然后在数据成功返回时设置此变量:

itunesAPI().itunesSearch({(song : songData) in
   self.tableData.append(song) // add the result to the list of data
   self.tableView.reloadData() // reload the table
})

然后将单元格设置为:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    var artistAndAlbum = self.tableData[indexPath.row]

    cell.textLabel?.text = artistAndAlbum.artistName
    cell.detailTextLabel?.text = artistAndAlbum.albumName

    return cell

}
相关问题