14
6

More than 3 years have passed since last update.

SwiftUIでNukeを使ってリモートの画像を表示する

Last updated at Posted at 2019-12-03

はじめに

SwiftUIを使い始めました。全てSwiftで宣言的にLayoutを記述でき、ReactiveXを使わなくてもデータをバインディングできて、すごくいいなと感じています!

さて、アプリを作るときは多くの場合画像ライブラリを使って画像を表示すると思います。私はNukeを使っているので、ここでは、Nukeを使ってリモートの画像を表示するSwiftUIのCustomViewを作成する方法を説明します。(Nuke以外も同じようにできると思います。)

CustomView

RemoteImageView.swift
import SwiftUI

struct RemoteImageView: View {
    @ObservedObject var remoteImage: RemoteImage
    var body: some View {
        Image(uiImage: remoteImage.image)
            .resizable()
            .aspectRatio(contentMode: .fit)
    }
}

struct RemoteImageView_Previews: PreviewProvider {
    static var previews: some View {
        RemoteImageView(remoteImage: RemoteImage(url: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/JRE-E231-500-for-JRyamanote-line.jpg/2560px-JRE-E231-500-for-JRyamanote-line.jpg")!))
    }
}

ObservableObject

ここで画像を読み込みます。
imageが変わるたびに変更がpublishされ、上のCustomViewに反映されます。

RemoteImage.swift
import Foundation
import SwiftUI

import Nuke

class RemoteImage: ObservableObject {
    @Published var image: UIImage

    private let url: URL

    init(url: URL, placeholder: UIImage = UIImage()) {
        self.image = placeholder
        self.url = url

        loadImage()
    }

    private func loadImage() {
        ImagePipeline.shared.loadImage(with: url) { [weak self] result in
            guard let self = self else { return }
            switch result {
            case .success(let response):
                self.image = response.image
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

使い方

SwiftUIのプロジェクトを作成すると自動生成されるContentViewで、RemoteImageViewを利用します。

ContentView.swift
import SwiftUI

struct ContentView: View {
    var body: some View {
        RemoteImageView(remoteImage: RemoteImage(url: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/JRE-E231-500-for-JRyamanote-line.jpg/2560px-JRE-E231-500-for-JRyamanote-line.jpg")!))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

表示はこんな感じです。山手線です。

スクリーンショット

以上です。

14
6
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
14
6