SPB Git

Repository Public

ImageLoader.swift 8.1 KB 186 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/Images/ImageLoader.swift10// Description      : chargement des photos d'inscriptions — miniature du11//                    service (`/api/img`), sinon l'image d'origine réduite à la12//                    taille utile ; cache mémoire et disque.13// Module           : VraiPrix14// Repository       : https://git.spboucher.ai/vrai-prix-ios-v315// Project Website  : https://www.vrai-prix.com16// Created          : 2026-11-2617// Last Modified    : 2026-11-2618//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import ImageIO92import SwiftUI93import UIKit9495actor ImageLoader {96    static let shared = ImageLoader()9798    private let session: URLSession99    private let memory = NSCache<NSString, UIImage>()100    private var inflight: [String: Task<UIImage?, Never>] = [:]101102    init() {103        let cfg = URLSessionConfiguration.default104        cfg.urlCache = URLCache(memoryCapacity: 24 << 20, diskCapacity: 300 << 20, directory: nil)105        cfg.requestCachePolicy = .returnCacheDataElseLoad106        cfg.timeoutIntervalForRequest = 15107        cfg.httpMaximumConnectionsPerHost = 6108        session = URLSession(configuration: cfg)109        memory.totalCostLimit = 96 << 20110    }111112    /// Image prête à afficher (au plus `maxPixel` de côté), ou nil.113    func image(for source: String, maxPixel: CGFloat) async -> UIImage? {114        let key = "\(Int(maxPixel))|\(source)"115        if let hit = memory.object(forKey: key as NSString) { return hit }116        if let t = inflight[key] { return await t.value }117        let session = self.session118        let t = Task<UIImage?, Never> {119            guard let url = URL(string: source), let s = url.scheme?.lowercased(), s == "https" || s == "http" else { return nil }120            // les sources d'annonces servent parfois en http : la version https est demandée121            var comps = URLComponents(url: url, resolvingAgainstBaseURL: false)122            comps?.scheme = "https"123            guard let u = comps?.url else { return nil }124            // miniature WebP du service (`/api/img`, largeurs 160 à 1280) ; sinon l'image d'origine réduite ici125            let w = [160, 320, 480, 640, 960, 1280].first { CGFloat($0) >= maxPixel } ?? 1280126            if let thumb = await APIClient.shared.url("api/img", query: ["u": u.absoluteString, "w": String(w)]),127               let img = await ImageLoader.fetch(thumb, session: session, maxPixel: maxPixel) {128                return img129            }130            return await ImageLoader.fetch(u, session: session, maxPixel: maxPixel)131        }132        inflight[key] = t133        let img = await t.value134        inflight[key] = nil135        if let img {136            memory.setObject(img, forKey: key as NSString, cost: Int(img.size.width * img.size.height * img.scale * img.scale * 4))137        }138        return img139    }140141    private static func fetch(_ url: URL, session: URLSession, maxPixel: CGFloat) async -> UIImage? {142        var req = URLRequest(url: url)143        req.setValue("image/webp,image/*;q=0.8", forHTTPHeaderField: "Accept")144        guard let (data, resp) = try? await session.data(for: req),145              (resp as? HTTPURLResponse).map({ (200..<300).contains($0.statusCode) }) ?? false,146              data.count > 64 else { return nil }147        guard let src = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }148        let opts: [CFString: Any] = [149            kCGImageSourceCreateThumbnailFromImageAlways: true,150            kCGImageSourceCreateThumbnailWithTransform: true,151            kCGImageSourceShouldCacheImmediately: true,152            kCGImageSourceThumbnailMaxPixelSize: maxPixel,153        ]154        guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary) else { return UIImage(data: data) }155        return UIImage(cgImage: cg)156    }157}158159/// Photo d'annonce : fondu à l'arrivée ; sans photo, le gabarit de la marque, jamais d'icône cassée.160struct RemoteImage: View {161    let source: String?162    var maxPixel: CGFloat = 640163    @State private var image: UIImage?164    @State private var failed = false165166    var body: some View {167        Rectangle().fill(Theme.surface2)168            .overlay {169                if let image {170                    Image(uiImage: image).resizable().aspectRatio(contentMode: .fill).transition(.opacity)171                } else if failed || source == nil {172                    BrandSymbol(style: .mono(Theme.ink3.opacity(0.45))).frame(width: 34, height: 34)173                }174            }175            .clipped()176            .task(id: source) {177                image = nil; failed = false178                guard let source else { return }179                let img = await ImageLoader.shared.image(for: source, maxPixel: maxPixel)180                if Task.isCancelled { return }181                withAnimation(.easeOut(duration: 0.25)) { image = img; failed = img == nil }182            }183            .accessibilityHidden(true)184    }185}186
Files main
Menu

Theme