-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoteImage.swift
88 lines (77 loc) · 2.53 KB
/
RemoteImage.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
// RemoteImage.swift
// Politifi
//
// Created by Ethan Hanlon on 1/18/21.
// Shows an image from URL. Do not allow users to insert their own URLs, as this is a potential security risk.
// Only use in rare cases where you don't want any caching. TODO: Elaborate
import SwiftUI
struct RemoteImage: View {
let resizable: Bool
var body: some View {
if resizable {
selectImage()
.resizable()
} else {
selectImage()
}
}
private enum loadState {
case loading, success, failure
}
private class Loader: ObservableObject {
var data = Data()
var state = loadState.loading
init(url: String) {
guard let parsedURL = URL(string: url) else {
print("Failed to grab image at: \(url)")
return
}
URLSession.shared.dataTask(with: parsedURL) { data, response, error in
if let data = data, data.count > 0 {
self.data = data
self.state = .success
} else {
self.state = .failure
}
DispatchQueue.main.async {
self.objectWillChange.send()
}
}.resume()
}
}
@ObservedObject private var loader: Loader
var loading: Image
var failure: Image
init(url: String, loading: Image = Image(systemName: "person.circle.fill"), resizable: Bool = true, failure: Image = Image(systemName: "multiply.circle")) {
_loader = ObservedObject(wrappedValue: Loader(url: url))
self.resizable = resizable
self.loading = loading
self.failure = failure
}
private func selectImage() -> Image {
switch loader.state {
case.loading:
return loading
case.failure:
return failure
default:
if let image = UIImage(data: loader.data) {
return Image(uiImage: image)
} else {
return failure
}
}
}
}
struct RemoteImage_Previews: PreviewProvider {
static var previews: some View {
Group {
//Turn on live preview to see the image load
// RemoteImage(url: "https://i.pinimg.com/originals/8e/06/5c/8e065c7a30d4724aeed6e5f9484b54ad.jpg")
// .previewLayout(.sizeThatFits)
// RemoteImage(url: "http://invalid")
// .previewLayout(.sizeThatFits)
}
}
}