0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UICollectionViewにAPIを使用して画像を表示させる

Last updated at Posted at 2021-07-21

完成形はこんな感じです

74BD4482-1E06-442A-A776-2E7B50551EF7_1_201_a.jpeg A883044C-7857-4A5F-9A03-E60DA83A7EBD_1_201_a.jpeg

機能説明

  • 上のTextFieldには検索したいキーワードと下のTextFieldには表示したい数を入力して、検索ボタンを押します
  • すると、UICollectionViewのCellに画像が表示されます。

コードと簡単解説

Podfile

Podfile
  pod 'SwiftyJSON'
  pod 'Alamofire'
  pod 'SDWebImage'

Model

SearchResultDatas
import Foundation

struct SearchResultDatas{
    
    var imageURLData = String()
  
}
  • func searchGetImageURL(searchKeyword:String,searchCount:Int){}では、searchCountの数値からマイナス1個分のデータを取得したいので、for文を用いています。

  • if jsonResult["hits"][needDataCount]["webformatURL"].string != nil{}else{break}では取得できるデータが無くなった時取得元の制限によって取得が出来なくなった時に、処理を終わらせる

AlamofireModel
import Foundation
import Alamofire
import SwiftyJSON

class AlamofireModel{
    
    var searchResultDatasArray = [SearchResultDatas]()
    
}

extension AlamofireModel{
    
    func searchGetImageURL(searchKeyword:String,searchCount:Int){
        
        AF.request("~~~~~~~~~APIKey~~~~~~~~~&q=\(searchKeyword)", method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { (response) in
            
            switch response.result{
            
            case.success:
                
                self.searchResultDatasArray = [] //以前のデータを削除
                
                let jsonResult:JSON = JSON(response.data as Any)
                
                for needDataCount in 0...searchCount - 1{
            
                    if jsonResult["hits"][needDataCount]["webformatURL"].string != nil{
                        
                        let jsonResult = SearchResultDatas(imageURLData: jsonResult["hits"][needDataCount]["webformatURL"].string!)
                        
                        self.searchResultDatasArray.append(jsonResult)
                        
                    }else{
                        
                        break  //取得できる"webformatURL"が無くなった時に処理を終わらせる
                        
                    }                    
                }
            
            case .failure:
                
                let error = NSError()
                print(error.debugDescription)
                break
                
            }           
        }       
    }    
}

View

  • 以前投稿した記事で簡単にですが、解説してますのでUIActivityIndicatorViewをご覧ください。
  • コメントでの質問でも大丈夫です 
ActivityIndicator
import Foundation
import UIKit

class ActivityIndicator:UIViewController{
    
    let uiActivityIndicator = UIActivityIndicatorView()
    
}

extension ActivityIndicator{
    
    func createIndicator(targetView:UIView){
        
        self.uiActivityIndicator.center = targetView.center
        self.uiActivityIndicator.color = .white
        self.uiActivityIndicator.style = .large
        
        targetView.addSubview(self.uiActivityIndicator)
        
    }   
}

Controller

  • searchKeywordTextFieldsearchCountTextFieldに入力された値をalamofireModel.searchGetImageURL()で検索したい画像と取得したい数として使用する。
ViewController
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var searchKeywordTextField: UITextField!
    @IBOutlet weak var searchCountTextField: UITextField!
    
    
    let alamofireModel = AlamofireModel()
    let activityIndicator = ActivityIndicator()
    
    
    override func viewDidLoad() {
        super.viewDidLoad() 
             
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        activityIndicator.createIndicator(targetView: self.view)
        
    }
    
    @IBAction func Search(_ sender: UIButton) {
        
        alamofireModel.searchGetImageURL(searchKeyword: searchKeywordTextField.text!, searchCount: Int(searchCountTextField.text!)!)
        
        activityIndicator.uiActivityIndicator.startAnimating()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            
            let collectionVC = self.storyboard?.instantiateViewController(identifier: "collectionVC") as! CollectionViewController
            
            collectionVC.receiveResultJSONArray = []
            collectionVC.receiveResultJSONArray = self.alamofireModel.searchResultDatasArray
            
            self.activityIndicator.uiActivityIndicator.stopAnimating()
            
            self.navigationController?.pushViewController(collectionVC, animated: true)
                       
        }       
    }   
}
CollectionViewController
import UIKit
import SDWebImage

class CollectionViewController: UIViewController{
    
    @IBOutlet weak var collectionView: UICollectionView!
      
    let collectionViewFlowLayout = UICollectionViewFlowLayout()
    
    var receiveResultJSONArray = [SearchResultDatas]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        collectionView.collectionViewLayout = collectionViewFlowLayout
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.reloadData()
    }

    }
       
extension CollectionViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.receiveResultJSONArray.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
        
        let cellImageView = cell.contentView.viewWithTag(1) as! UIImageView
        
        cellImageView.frame = CGRect(x: cell.bounds.minX, y: cell.bounds.minY, width: cell.frame.size.width, height: cell.frame.size.height)
        
        cellImageView.contentMode = .scaleAspectFill
        
        cellImageView.sd_setImage(with: URL(string: self.receiveResultJSONArray[indexPath.row].imageURLData), completed: nil)
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            
            return CGSize(width: collectionView.frame.size.width / 4 - 10, height: collectionView.frame.size.width / 4 - 10)
            
        }
}

終わり

解説と呼べることはしてないので
ご指摘やご質問などがございましたら、コメントまでよろしくお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?