Swipe-That_pic/Swipe That Pic/Views/PhotoTumbnailFromStringView.swift

74 lines
2.2 KiB
Swift
Raw Normal View History

2024-07-26 13:16:48 +00:00
//
// PhotoTumbnailView.swift
// Swipe That Pic
//
// Created by Amine Bou on 27/07/2024.
//
import Foundation
import Photos
import SwiftUI
struct PhotoThumbnailFromStringView: View {
@EnvironmentObject var photoLibraryService: PhotosService
@State private var image: Image?
@State var localIdentifier: String?
func loadImageAsset(
targetSize: CGSize = PHImageManagerMaximumSize
) async {
if (localIdentifier != nil) {
guard let uiImage = try? await photoLibraryService
.fetchImage(
byLocalIdentifier: 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
image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(
width: proxy.size.width,
height: proxy.size.width
)
.clipped()
}
// We'll also make sure that the photo will
// be square
.aspectRatio(1, contentMode: .fit)
} 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: localIdentifier) {
await loadImageAsset()
}
// Finally, when the view disappears, we need to free it
// up from the memory
.onDisappear {
image = nil
}
}
}