-
Notifications
You must be signed in to change notification settings - Fork 14
/
FirebaseImage.swift
64 lines (51 loc) · 1.37 KB
/
FirebaseImage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// FirebaseImage.swift
// julienne
//
// Created by Ben McMahen on 2019-06-28.
// Copyright © 2019 Ben McMahen. All rights reserved.
//
import SwiftUI
import Combine
import FirebaseStorage
final class Loader : BindableObject {
let didChange = PassthroughSubject<Data?, Never>()
var data: Data? = nil {
didSet { didChange.send(data) }
}
init(_ id: String){
let url = "images/thumb-sm@\(id)"
let storage = Storage.storage()
let ref = storage.reference().child(url)
ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("\(error)")
}
DispatchQueue.main.async {
self.data = data
}
}
}
}
let placeholder = UIImage(named: "placeholder.jpg")!
struct FirebaseImage : View {
init(id: String) {
self.imageLoader = Loader(id)
}
@ObjectBinding private var imageLoader : Loader
var image: UIImage? {
imageLoader.data.flatMap(UIImage.init)
}
var body: some View {
Image(uiImage: image ?? placeholder)
.resizable()
.aspectRatio(contentMode: .fill)
}
}
#if DEBUG
struct FirebaseImage_Previews : PreviewProvider {
static var previews: some View {
FirebaseImage(id: "random")
}
}
#endif