LoginSignup
0
2

More than 1 year has passed since last update.

【Swift】APIから画像を取得して表示する

Posted at

どういうことか

APIを叩くとレスポンスでURLが返ってくる。
それを元に画像を表示したい。
今回はマジック・ザ・ギャザリングのAPIを使ってカード画像を表示しよう。

APIを叩く方法などは割愛。

Kingfisher

画像の変換にはライブラリのKingfisherを使う。

cocoaPodsでインストールする。

pod 'Kingfisher'

使い方はカンタン。
今回はcollectionViewに表示させることを想定している。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CardCollectionViewCell.reusableIdentifier, for: indexPath) as! CardCollectionViewCell

        if let cardImage = cards?.cards[indexPath.row].imageUrl {
            cell.imageView.kf.setImage(with: URL(string: cardImage))
        }

        return cell
    }

ところがエラーが出て表示しない。
元の画像URLが https ではなく http であるため使うことができない。
httpが使えるようにする。

これで無事表示されました。

Simulator Screen Shot - iPod touch (7th generation) - 2021-06-03 at 23.35.16.png

ちなみにこのカードは全カードを取得して1番上にあるカードで思い入れは特に無し。
好きなカードは走り回るスカージです。
おわり(´・ω・`)

0
2
1

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
2