Making an attempt to persists an array of UIImage and return an array of the saved file paths in func encodeReview, however maintain hitting
Mutation of captured var ‘encodedImages’ in concurrently-executing code
at encodedImages.append(_url)
The objective is to avoid wasting an array of Evaluate with the connected imageURL as JSON so I can re-load the photographs.
//
// Evaluate.swift
// resRec
//
// Created by King F. Wong on 03/10/2023.
//
import Basis
import UIKit
struct Evaluate: Identifiable {
let id: UUID
var restaurant: Restaurant
var userReview: UserReview
init(id: UUID=UUID(),
restaurant: Restaurant,
userTags: [Tag],
userOverallRating: Double,
userFoodRating: Double,
userAmbianceRating: Double,
userServicesRating: Double,
userImages: [UIImage]
) {
self.id = id
self.restaurant = restaurant
self.userReview = UserReview(
tags: userTags,
overallRating: userOverallRating,
foodRating: userFoodRating,
ambianceRating: userAmbianceRating,
servicesRating: userServicesRating,
photos: userImages
)
}
}
extension Evaluate {
struct UserReview: Identifiable {
let id: UUID
var tags: [Tag]
var overallRating: Double
var foodRating: Double
var ambianceRating: Double
var servicesRating: Double
var photos: [UIImage]
init(id: UUID=UUID(), tags: [Tag], overallRating: Double, foodRating: Double, ambianceRating: Double, servicesRating: Double, photos: [UIImage]) {
self.id = id
self.tags = tags
self.overallRating = overallRating
self.foodRating = foodRating
self.ambianceRating = ambianceRating
self.servicesRating = servicesRating
self.photos = photos
}
}
}
extension Evaluate {
// load pattern photographs
static let sampleReviewImages: [UIImage]
}
extension Evaluate {
func encodeReview (evaluation: Self) async {
var encodedImages: [URL] = []
let encodedRestaurant = evaluation.restaurant.encodingRestaurant(rawRestaurant: evaluation.restaurant)
attempt? await Process {
for userImage in evaluation.userReview.photos {
if let _url = attempt? await saveImage(picture: userImage) {
encodedImages.append(_url)
}
}
}
}
}
extension Evaluate {
static let globalReviews: [Review] =
[
Review(restaurant: Restaurant.sampleData,
userTags: sampleReviewTags(),
userOverallRating: 9.0,
userFoodRating: 9.0,
userAmbianceRating: 8.5,
userServicesRating: 8.0,
userImages: sampleReviewImages
)
]
}
func saveImage(picture: UIImage) async throws -> URL {
if let imageData = picture.jpegData(compressionQuality: 1.0) {
let supervisor = FileManager()
if let docUrl = supervisor.urls(for: .documentDirectory, in: .userDomainMask).first{
let uniqueName = NSDate.timeIntervalSinceReferenceDate
let url = docUrl.appendingPathComponent("(uniqueName).jpg")
let activity = Process {
attempt imageData.write(to:url)
return url
}
}
}
}