楽天APIで商品のランキングを取得と表示（性別と年齢から検索）



#コード

##Model

```Swift:ItemDetailDatas
struct ItemDetailDatas{
    
    let rank:Int?
    let mediumImageURL:String?
    let itemName:String?
    let itemPrice:String?
}

```
```Swift:AlamofireProcess
import Alamofire
import SwiftyJSON
import UIKit

class AlamofireProcess{
    
    private var itemDetailResultArray = [ItemDetailDatas]()
}

extension AlamofireProcess{
    
    public func getItemDetailData(targetGender:Int?,targetAge:Int?,completion:@escaping ([ItemDetailDatas]?,Error?) -> Void){
        
        guard let gender = targetGender else { return }
        guard let age = targetAge else { return }
        
        let apiKey = "https://app.rakuten.co.jp/services/api/IchibaItem/Ranking/20170628?format=json&age=\(age)&sex=\(gender)&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)
                print(detailData)
                for dataCount in 0..<detailData["Items"].count{
                    
                    
                    if let getRank = detailData["Items"][dataCount]["Item"]["rank"].int,
                       let getmediumImageUrl = detailData["Items"][dataCount]["Item"]["mediumImageUrls"][0]["imageUrl"].string,
                       let getItemName = detailData["Items"][dataCount]["Item"]["itemName"].string,
                       let getItemPrice = detailData["Items"][dataCount]["Item"]["itemPrice"].string{
                        
                        itemDetailResultArray.append(ItemDetailDatas(rank: getRank,
                                                                     mediumImageURL: getmediumImageUrl,
                                                                     itemName: getItemName,
                                                                     itemPrice: getItemPrice))
                        
                    }
                }
                print(itemDetailResultArray)
                completion(itemDetailResultArray, nil)
                
            case .failure(let error):
                
                completion(nil, error)
            }
        }
    }
    
}
```


##View

###Main.storyboard

<img width="150" alt="DA31A461-B3FD-4DE2-A4B3-909BE2DE85CF_4_5005_c.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/8370203f-9d1b-a782-f06f-c28f4d7fd414.jpeg">


###ResultTableViewCell

<img width="200" alt="539AC1D2-450C-4913-8D91-F3D54FDA2B03_4_5005_c.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/3c5518f3-705a-0d3d-755d-2bd5e542adfa.jpeg">

```Swift:ResultTableViewCell
import UIKit

class ResultTableViewCell: UITableViewCell {

    @IBOutlet weak var rankLabel: UILabel!
    @IBOutlet weak var mediumImageView: UIImageView!
    @IBOutlet weak var itemNameLabel: UILabel!
    @IBOutlet weak var itemPriceLabel: 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 = ""
        mediumImageView.image = UIImage(named: "")
        itemNameLabel.text = ""
        itemPriceLabel.text = ""
    }
    
}
```

##Controller

```Swift:ViewController
import UIKit
import SDWebImage

class ViewController: UIViewController {

 
    @IBOutlet weak var selectGenderSegment: UISegmentedControl!
    @IBOutlet weak var selectAgeSegment: UISegmentedControl!
    @IBOutlet weak var resultTableView: UITableView!
    
    private let alamofireProcess = AlamofireProcess()
    
    private var cellContentsArray = [ItemDetailDatas]()
    
    private let genderContents = [1,0]
    private let ageContents = [10,20,30,40,50]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        resultTableView.register(UINib(nibName: "ResultTableViewCell", bundle: nil), forCellReuseIdentifier: "ResultDetailCell")
        resultTableView.delegate = self
        resultTableView.dataSource = self
        
    }


    @IBAction func search(_ sender: UIButton) {
        
        alamofireProcess.getItemDetailData(targetGender: genderContents[selectGenderSegment.selectedSegmentIndex], targetAge: ageContents[selectAgeSegment.selectedSegmentIndex]) { result, error in
        
            if error != nil{
                
                return
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {[self] in
                
                cellContentsArray = result!
                resultTableView.reloadData()
            }
        }
    }
}

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

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: "ResultDetailCell", for: indexPath) as! ResultTableViewCell
        
        cell.rankLabel.text = String(cellContentsArray[indexPath.row].rank!) + "位"
        cell.mediumImageView.sd_setImage(with: URL(string: cellContentsArray[indexPath.row].mediumImageURL!), completed: nil)
        cell.itemNameLabel.text = cellContentsArray[indexPath.row].itemName
        cell.itemPriceLabel.text = cellContentsArray[indexPath.row].itemPrice
        
        return cell
    }
}
```

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