74 lines
2.1 KiB
Swift
74 lines
2.1 KiB
Swift
//
|
|
// PhotoTumbnailView.swift
|
|
// Swipe That Pic
|
|
//
|
|
// Created by Amine Bou on 27/07/2024.
|
|
//
|
|
|
|
import Foundation
|
|
import Photos
|
|
import SwiftUI
|
|
|
|
struct PhotoThumbnailView: View {
|
|
@EnvironmentObject var photoLibraryService: PhotosService
|
|
@State private var image: Image?
|
|
@Binding var asset: PHAsset?
|
|
|
|
func loadImageAsset(
|
|
targetSize: CGSize = PHImageManagerMaximumSize
|
|
) async {
|
|
if (asset != nil) {
|
|
guard let uiImage = try? await photoLibraryService
|
|
.fetchImage(
|
|
byLocalIdentifier: asset!.localIdentifier,
|
|
targetSize: targetSize
|
|
) else {
|
|
image = nil
|
|
return
|
|
}
|
|
image = Image(uiImage: uiImage)
|
|
} else {
|
|
image = nil
|
|
}
|
|
}
|
|
|
|
var body: some View {
|
|
ZStack {
|
|
// Show the image if it's available
|
|
if let image = image {
|
|
GeometryReader { proxy in
|
|
NavigationLink(destination: BigPicture(image: image)) {
|
|
image
|
|
.resizable()
|
|
.aspectRatio(contentMode: .fill)
|
|
.frame(
|
|
width: proxy.size.width,
|
|
height: proxy.size.width
|
|
)
|
|
.clipped()
|
|
}
|
|
|
|
}
|
|
} else {
|
|
// Otherwise, show a gray rectangle with a
|
|
// spinning progress view
|
|
Rectangle()
|
|
.foregroundColor(.gray)
|
|
.aspectRatio(1, contentMode: .fit)
|
|
ProgressView()
|
|
}
|
|
}
|
|
// We need to use the task to work on a concurrent request to
|
|
// load the image from the photo library service, which
|
|
// is asynchronous work.
|
|
.task(id: asset?.localIdentifier) {
|
|
await loadImageAsset()
|
|
}
|
|
// Finally, when the view disappears, we need to free it
|
|
// up from the memory
|
|
.onDisappear {
|
|
image = nil
|
|
}
|
|
}
|
|
}
|