今回の内容
- 楽天APIを使用して取得してきたデータを
UICollectionView
に表示させています。
コード
Model
ItemResultDetailModel
struct ItemResultDetailModel{
let mediumImageUrl:String?
let itemName:String?
let itemPrice:Int?
let shopName:String?
}
AlamofireProcess
import Alamofire
import SwiftyJSON
class AlamofireProcess{
private var resultDetailDatas = [ItemResultDetailModel]()
}
extension AlamofireProcess{
public func getItemDetailData(searchKey:String?,completion:@escaping([ItemResultDetailModel]?,Error?) -> Void){
guard let key = searchKey else { return }
let apiKey = "https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706?format=json&keyword=\(key.urlEncoded)&applicationId=作成したアプリID"
AF.request(apiKey, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON {[self] response in
switch response.result{
case .success:
let getdata = JSON(response.data as Any)
resultDetailDatas = []
print(getdata)
for dataCount in 0..<30{
if let getMediumImageUrl = getdata["Items"][dataCount]["Item"]["mediumImageUrls"][0]["imageUrl"].string,
let getItemName = getdata["Items"][dataCount]["Item"]["itemName"].string,
let getItemPrice = getdata["Items"][dataCount]["Item"]["itemPrice"].int,
let getShopName = getdata["Items"][dataCount]["Item"]["shopName"].string{
print(getMediumImageUrl)
print(getItemName)
print(getItemPrice)
print(getShopName)
resultDetailDatas.append(ItemResultDetailModel(mediumImageUrl: getMediumImageUrl,
itemName: getItemName,
itemPrice: getItemPrice,
shopName: getShopName))
}
}
completion(resultDetailDatas, nil)
case .failure(let error):
completion(nil, error)
}
}
}
}
extension String{
var urlEncoded:String{
let charset = CharacterSet.alphanumerics.union(.init(charactersIn: "/?-._~"))
let remove = removingPercentEncoding ?? self
return remove.addingPercentEncoding(withAllowedCharacters: charset) ?? remove
}
}
View
Main.storyboard

ResultItemListCell

ResultItemListCell
import UIKit
class ResultItemListCell: UICollectionViewCell {
@IBOutlet weak var mediumImageView: UIImageView!
@IBOutlet weak var itemNameLabel: UILabel!
@IBOutlet weak var itemPriceLabel: UILabel!
@IBOutlet weak var shopNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func prepareForReuse() {
super.prepareForReuse()
mediumImageView.image = UIImage(named: "")
itemNameLabel.text = ""
itemPriceLabel.text = ""
shopNameLabel.text = ""
}
}
Controller
ViewController
import UIKit
import SDWebImage
class ViewController: UIViewController {
@IBOutlet weak var resultCollectionView: UICollectionView!
@IBOutlet weak var searchTextField: UITextField!
@IBOutlet weak var searchButton: UIButton!
private let alamofireProcess = AlamofireProcess()
private let cellLayout = UICollectionViewFlowLayout()
private var cellContentsArray = [ItemResultDetailModel]()
private var judgeChangeViewPointYBool = true
override func viewDidLoad() {
super.viewDidLoad()
resultCollectionView.register(UINib(nibName: "ResultItemListCell", bundle: nil), forCellWithReuseIdentifier: "ItemDetailCell")
resultCollectionView.dataSource = self
resultCollectionView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cellLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
resultCollectionView.collectionViewLayout = cellLayout
}
@IBAction func search(_ sender: UIButton) {
alamofireProcess.getItemDetailData(searchKey: searchTextField.text) { result, error in
if error != nil{
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {[self] in
cellContentsArray = result!
resultCollectionView.reloadData()
}
}
}
}
extension ViewController:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellContentsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemDetailCell", for: indexPath) as! ResultItemListCell
cell.mediumImageView.sd_setImage(with: URL(string: cellContentsArray[indexPath.row].mediumImageUrl!), completed: nil)
cell.itemNameLabel.text = cellContentsArray[indexPath.row].itemName
cell.itemPriceLabel.text = String(cellContentsArray[indexPath.row].itemPrice!)
cell.shopNameLabel.text = cellContentsArray[indexPath.row].shopName
return cell
}
}
extension ViewController:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width / 2 - 10, height: collectionView.frame.height / 2 - 10)
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。