楽天API トラベル関係からランキングを取得

#今回の内容

* `UISegmentedControl`で表示するランキングを選択します。
* `UITableView`に取得してきた`順位、画像、名前、所在の都道府県`を表示します。

#コード

##Model


```Swift:HotelDetailDatas
struct HotelDetailDatas{
    
    let rank:Int?
    let hotelImageUrl:String?
    let hotelName:String?
    let middleClassName:String?
}
```
```Swift:AlamofireProcess
import Alamofire
import SwiftyJSON

class AlamofireProcess{
    
    private var privateItemDetailArray = [HotelDetailDatas]()
}

extension AlamofireProcess{
    
    public func getItemDetailDatas(targetGenre:String?,completion: @escaping ([HotelDetailDatas]?,Error?) -> Void){
     
        guard let genre = targetGenre else { return }

        
        let apiKey = "https://app.rakuten.co.jp/services/api/Travel/HotelRanking/20170426?format=json&genre=\(genre)&applicationId=アプリID" 
        
        AF.request(apiKey, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON {[self] response in
            
            switch response.result{
                
            case .success:
                
                let detailData = JSON(response.data as Any)
                privateItemDetailArray = []
                                
                for dataCount in 0...detailData["Rankings"][0]["Ranking"]["hotels"].count - 1{
                    
                    if let getRank = detailData["Rankings"][0]["Ranking"]["hotels"][dataCount]["hotel"]["rank"].int,
                       let getHotelImageUrl = detailData["Rankings"][0]["Ranking"]["hotels"][dataCount]["hotel"]["hotelImageUrl"].string,
                       let getHotelName = detailData["Rankings"][0]["Ranking"]["hotels"][dataCount]["hotel"]["hotelName"].string,
                       let getMiddleClassName = detailData["Rankings"][0]["Ranking"]["hotels"][dataCount]["hotel"]["middleClassName"].string{
                        
                        
                        privateItemDetailArray.append(HotelDetailDatas(rank:getRank,
                                                                      hotelImageUrl: getHotelImageUrl,
                                                                      hotelName: getHotelName,
                                                                      middleClassName: getMiddleClassName))
                    }
                
                }
                completion(privateItemDetailArray, nil)
                
            case .failure(let error):
                
                completion(nil, error)
            }
        }
        
    }
}
```


##View

###Main.storyboard

<img width="150" alt="CD8DD250-0D06-4AA9-893E-F34BAD6431C4_4_5005_c.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/d8b81d06-fb44-693f-e7c8-42fb493eb3f0.jpeg">

###TableViewCustomCell
<img width="300" alt="89CD32B8-3481-4910-92FF-805BD4AEDDCD_4_5005_c.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/225a48f4-9af3-b09a-f995-a208ec01dbb3.jpeg">

```Swift:TableViewCustomCell
import UIKit

class TableViewCustomCell: UITableViewCell {

    @IBOutlet weak var rankLabel: UILabel!
    @IBOutlet weak var hotelImageView: UIImageView!
    @IBOutlet weak var hotelNameLabel: UILabel!
    @IBOutlet weak var middleClassNameLabel: UILabel!    
    
    override func awakeFromNib() {
        super.awakeFromNib()

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }
 
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        
        rankLabel.text = ""
        hotelImageView.image = UIImage(named: "")
        hotelNameLabel.text = ""
        middleClassNameLabel.text = ""
    }
}
```

##Controller


```Swift:
import UIKit
import SDWebImage

class ViewController: UIViewController {

    @IBOutlet weak var selectGenreSegment: UISegmentedControl!
    @IBOutlet weak var resultTableView: UITableView!
    
    private let alamofireProcess = AlamofireProcess()
    
    private var cellContentsArray = [HotelDetailDatas]()

    private let selectGenreResultArray = ["all","onsen","premium"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        resultTableView.register(UINib(nibName: "TableViewCustomCell", bundle: nil), forCellReuseIdentifier: "ItemDetailCell")
        resultTableView.delegate = self
        resultTableView.dataSource = self
    }

    @IBAction func search(_ sender: UIButton) {
        
        alamofireProcess.getItemDetailDatas(targetGenre: selectGenreResultArray[selectGenreSegment.selectedSegmentIndex]) { result, error in
            
            if error != nil{
                
                return
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {[self] in

                cellContentsArray = []
                cellContentsArray = result!
                resultTableView.reloadData()
            }
        }
    }
    
}

extension ViewController:UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return tableView.frame.height / 3.4
    }
}

extension ViewController:UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return cellContentsArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemDetailCell", for: indexPath) as! TableViewCustomCell
        
        cell.rankLabel.text = "\(String(cellContentsArray[indexPath.row].rank!))位"
        cell.hotelImageView.sd_setImage(with: URL(string: cellContentsArray[indexPath.row].hotelImageUrl!), completed: nil)
        cell.hotelNameLabel.text = cellContentsArray[indexPath.row].hotelName
        cell.middleClassNameLabel.text = cellContentsArray[indexPath.row].middleClassName
        
        return cell
    }
}
```

# 終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。