SwitUI-实现URL图片显示

实现方法一(纯使用SwiftUI)

import SwiftUI

struct WebImage: View {
    @ObservedObject var imageLoader: ImageLoader
    @State var image: UIImage = UIImage()

    init(withURL url: String) {
        imageLoader = ImageLoader(urlString:url)
    }

    var body: some View {
        VStack {
            //在这里,我们可以直接检查imageLoader的data属性。如果为零,则使用空的UIImage,否则可以使用数据创建UIImage。设置完数据后,@ Published将通知ImageView,它将使用imageLoader中数据的更新版本重新加载Image。
            Image(uiImage: imageLoader.data != nil ? UIImage(data:imageLoader.data!)! : UIImage())
                .resizable()
                .aspectRatio(contentMode: .fit)
        }
    }
}

class ImageLoader: ObservableObject {
    //通过使用@Published属性包装器,我们不需要像PassthroughSubject那样创建自己的发布者并通知我们的订阅者。属性包装器会处理它。
    @Published var data:Data?
    
    init(urlString: String) {
        guard let url = URL(string: urlString) else { return }
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else { return }
            DispatchQueue.main.async { self.data = data }
        }
        task.resume()
    }
}

#if DEBUG
struct WebImage_Previews: PreviewProvider {
    static var previews: some View {
        WebImage(withURL: "https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1158873959,778733211&fm=26&gp=0.jpg")
    }
}
#endif

实现方法二(纯使用SwiftUI和Combine)

import SwiftUI
import Combine

struct WebImage: View {
    @ObservedObject var imageLoader: ImageLoader
    @State var image: UIImage = UIImage()

    init(withURL url: String) {
        imageLoader = ImageLoader(urlString:url)
    }

    var body: some View {
        VStack {
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
        }.onReceive(imageLoader.didChange) { data in
            self.image = UIImage(data: data) ?? UIImage()
        }
    }
}

class ImageLoader: ObservableObject {
    var didChange = PassthroughSubject()
    var data = Data() {
        didSet {
            didChange.send(data)
        }
    }
    
    init(urlString: String) {
        guard let url = URL(string: urlString) else { return }
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else { return }
            DispatchQueue.main.async { self.data = data }
        }
        task.resume()
    }
}

#if DEBUG
struct WebImage_Previews: PreviewProvider {
    static var previews: some View {
        WebImage(withURL: "https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1158873959,778733211&fm=26&gp=0.jpg")
    }
}
#endif

最终效果:


截屏2019-12-0714.19.47.png

你可能感兴趣的:(SwitUI-实现URL图片显示)