楽天ブックスAPIから画像、本のタイトル、著者名、価格を取得して表示

#今回の内容

<img width="150" alt="158DFC87-A3A4-4032-B4D5-2B5FB786C5F0_1_201_a.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/b0604e94-5bcd-f424-822c-66bdfa547c51.jpeg">

* 上の画像は取得したデータを表示する`Cell`を見える様にする為に仮の値を入れています。

#コード

##Model

```Swift:BookDetailDatas
struct BookDetailDatas{
    
    let mediumImageUrl:String?
    let bookTitle:String?
    let author:String?
    let itemPrice:Int?
}
```

```Swift:
import Alamofire
import SwiftyJSON

class Alamofire{
    
    private var privateMediumImageUrl:String?
    private var privateBookTitle:String?
    private var privateAuthor:String?
    private var privateItemPrice:Int?
    
    private var bookDetailDataArray = [BookDetailDatas]()

}

extension Alamofire{
    
    public func getBookDetailDatas(searchKeyWord:String?,completion: @escaping ([BookDetailDatas]?,Error?) -> Void){
        
        guard let keyword = searchKeyWord else { return }
        
        let apiKey = ""
        
        AF.request(apiKey, method: .get, parameters: nil, encoding: JSONEncoding.default).response { [self] respnse in
            
            switch respnse.result{
                
            case .success:
                let data = JSON(respnse.data as Any)
                
                print(data)
                for itemCount in 0..<data["Items"].count{
                    
                    getDataNilCheck(imageurl: data["Items"][itemCount]["Item"]["mediumImageUrl"].string,
                                    title: data["Items"][itemCount]["Item"]["title"].string,
                                    author: data["Items"][itemCount]["Item"]["author"].string,
                                    itemPrice: data["Items"][itemCount]["Item"]["itemPrice"].int)
                    
                    bookDetailDataArray.append(BookDetailDatas(mediumImageUrl: privateMediumImageUrl,
                                                               bookTitle: privateBookTitle,
                                                               author: privateAuthor,
                                                               itemPrice: privateItemPrice))
                    
                }
                print(bookDetailDataArray)
           completion(bookDetailDataArray, nil)
                
            case .failure(let error):
                
                completion(nil, error)
            }
        }
    }
}


extension Alamofire{
    
    private func getDataNilCheck(imageurl:String?,title:String?,author:String?,itemPrice:Int?){
        
        if imageurl != nil{
            
            privateMediumImageUrl = imageurl
            
        }else{
            
            privateMediumImageUrl = ""
        }
        
        if title != nil{
            
            privateBookTitle = title
        }else{
            
            privateBookTitle = "読み込みエラー"
        }
        
        if author != nil{
            
            privateAuthor = author
        }else{
            
            privateAuthor = "読み込みエラー"
        }
        
        if itemPrice != nil{
            
            privateItemPrice = itemPrice
        }else{
            
            privateItemPrice = 0000
        }
        
    }
}


extension String{
    
    var urlEncoded:String{
        
        let charset = CharacterSet.alphanumerics.union(.init(charactersIn: "/?-._~"))
        let remove = removingPercentEncoding ?? self
        
        return remove.addingPercentEncoding(withAllowedCharacters: charset) ?? remove
    }
}

```

##View

```Swift:TableViewCustomCell
import UIKit

class TableViewCustomCell: UITableViewCell {

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

##Controller

```Swift:ViewController
import UIKit
import SDWebImage

class ViewController: UIViewController {

    @IBOutlet weak var searhResultTableView: UITableView!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var searchButton: UIButton!
    
    private let alamofire = Alamofire()
    
    private var cellContentsArray = [BookDetailDatas]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        searhResultTableView.register(UINib(nibName: "TableViewCustomCell", bundle: nil), forCellReuseIdentifier: "BookDetailCell")
        searhResultTableView.delegate = self
        searhResultTableView.dataSource = self
        
    }

    @IBAction func search(_ sender: UIButton) {
        
        if searchTextField.text!.count > 0{
            
            alamofire.getBookDetailDatas(searchKeyWord: searchTextField.text) { detail, error in
                
                if error != nil{
                    
                    return
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 5) {[self] in
                    
                    cellContentsArray = detail!
                    searhResultTableView.reloadData()
                }
            }
        }
    }
    
}

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

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: "BookDetailCell", for: indexPath) as! TableViewCustomCell
        
        cell.bookImageView.sd_setImage(with: URL(string: cellContentsArray[indexPath.row].mediumImageUrl!), completed: nil)
        cell.bookTitleLabel.text = cellContentsArray[indexPath.row].bookTitle
        cell.authorLabel.text = cellContentsArray[indexPath.row].author
        cell.itemPriceLabel.text = "\(String(cellContentsArray[indexPath.row].itemPrice!))円"
        
        return cell
    }
}

```


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