I've got a little swiftUI program that displays photos from a given day as stacks of photos for each year. Simplified code below. I read the photos into resultPhotos as a dictionary with each key the year, and each value a PHFetchResult. I then loop through each year in the dictionary and create myImageStack with the photos for that year.
Tested with around 100 photos, this is very slow. The culprit appears to be building the stack of images in myImageStack.
I'd like to try to build myImageStack asynchronously so as to not freeze the UI. Any guidance on how to do that? Most of the async/await examples I've found are built around returning data, but I'm trying to return a view that will be used in a ForEach loop. I feel like I'm missing something fundamental here.
(I realize that many of the images are completely covered in myImageStack, so perhaps I should be simplifying that view as well. But as the images are stacked randomly, you can see pieces of some of the images in the stack and I'd like to maintain that.)
import SwiftUI
import Foundation
import Photos
struct PhotosOverviewView_simplified: View {
var body: some View {
let photos = PhotosModel()
let _ = photos.getPhotoAuthorizationStatus()
let resultPhotos = photos.getAllPhotosOnDay(monthAbbr:"Feb", day:16)
NavigationStack{
ScrollView(.vertical){
VStack(alignment: .center){
//For each year, create a stack of photos
ForEach(Array(resultPhotos.keys).sorted(), id: \.self) { key in
let stack = myImageStack(resultsPhotos: resultPhotos[key]!)
NavigationLink(destination: PhotosYearView(year: key, resultsPhotos: resultPhotos[key]!)){
stack
.padding()
}
}
}
.frame(maxWidth: .infinity)
}
}
}
}
struct myImageStack: View {
let resultsPhotos: PHFetchResult<PHAsset>
var body: some View {
let collection = PHFetchResultCollection(fetchResult: resultsPhotos)
ZStack{
ForEach(collection, id: \.localIdentifier){ p in
Image(uiImage: p.getAssetThumbnail())
.resizable()
.scaledToFit()
.border(Color.white, width:10)
.shadow(color:Color.black.opacity(0.2), radius:5, x:5, y:5)
.frame(width: 200, height: 200)
.rotationEffect(.degrees(Double.random(in:-25...25)))
}
}
}
}