Files
sodalive-ios/SodaLive/Sources/Chat/Character/Banner/AutoSlideCharacterBannerView.swift
Yu Sung 8c58c08a85 perf(banner): TabView 프리로딩 완화·다운샘플링·요청취소 적용
배너/캐러셀에서 인접 페이지 프리로딩과 원본 해상도 디코딩으로
발생하던 메모리 스파이크와 중복 로드를 완화했습니다.

- 각 페이지에서 이미지 URL을 onAppear에 바인딩, onDisappear에 nil 해제
  → 인접 페이지 프리로딩 시 중복 로드·디코딩 방지, 요청 취소 실효
- 모든 KFImage에 cancelOnDisappear(true) 일관 적용
- 큰 배너 이미지에 downsampling(size:) 적용(디코딩 메모리 절감)
- 자동 슬라이드 주기 3초 → 4초로 완화(동시 로드 빈도 감소)
- TabView 페이지를 서브뷰로 분리하여 뷰 로직 단순화 및 재사용성 향상

결과: 동시 디코딩 감소, 피크 메모리 사용량 하락, 자동 슬라이드 안정성 개선
2025-10-23 15:31:52 +09:00

116 lines
3.5 KiB
Swift

//
// AutoSlideCharacterBannerView.swift
// SodaLive
//
// Created by klaus on 8/29/25.
//
import SwiftUI
import Kingfisher
struct AutoSlideCharacterBannerView: View {
var items: [CharacterBannerResponse] = []
var onTap: (CharacterBannerResponse) -> Void = { _ in }
@State private var currentIndex: Int = 0
@State private var height: CGFloat = 0
private let timer = Timer.publish(every: 4, on: .main, in: .common).autoconnect()
var body: some View {
VStack(spacing: 8) {
TabView(selection: $currentIndex) {
ForEach(0..<items.count, id: \.self) { index in
let item = items[index]
AutoSlideCharacterBannerPage(
item: item,
width: screenSize().width,
height: height,
onTap: onTap
)
.tag(index)
}
}
.tabViewStyle(.page(indexDisplayMode: .never))
.frame(maxWidth: .infinity)
.frame(height: height)
.onAppear {
self.height = screenSize().width * 0.53
}
.onDisappear {
timer.upstream.connect().cancel()
}
.onReceive(timer) { _ in
guard !items.isEmpty else { return }
withAnimation { currentIndex = (currentIndex + 1) % items.count }
}
HStack(spacing: 4) {
ForEach(0..<items.count, id: \.self) { index in
Capsule()
.foregroundColor(
index == currentIndex
? .button
: .gray90
)
.frame(
width: index == currentIndex ? 18 : 6,
height: 6
)
.tag(index)
}
}
}
}
}
#Preview {
AutoSlideCharacterBannerView(
items: [
CharacterBannerResponse(characterId: 1, imageUrl: "https://picsum.photos/1000/300")
]
)
.padding()
.background(Color.black)
}
private struct AutoSlideCharacterBannerPage: View {
let item: CharacterBannerResponse
let width: CGFloat
let height: CGFloat
let onTap: (CharacterBannerResponse) -> Void
@State private var boundURL: URL?
var body: some View {
Group {
if let boundURL {
KFImage(boundURL)
.placeholder { Color.gray.opacity(0.2) }
.retry(maxCount: 2, interval: .seconds(1))
.cancelOnDisappear(true)
.downsampling(size: CGSize(width: width, height: height))
.resizable()
.scaledToFill()
.frame(width: width, height: height)
.clipped()
.cornerRadius(12)
} else {
Color.clear
.frame(width: width, height: height)
.cornerRadius(12)
}
}
.contentShape(Rectangle())
.onTapGesture { onTap(item) }
.onAppear {
let encoded = item.imageUrl.addingPercentEncoding(
withAllowedCharacters: .urlQueryAllowed
) ?? item.imageUrl
boundURL = URL(string: encoded)
}
.onDisappear {
boundURL = nil
}
}
}