Skip to content

Conversation

@youn9k
Copy link
Member

@youn9k youn9k commented Nov 26, 2024

🤔 배경

스티커 이모지를 네트워킹을 통해 비동기로 불러오는데, 네트워크 환경에 따라 불러오는 속도가 느려 사용자 경험이 좋지 않았습니다.

📃 작업 내역

  • 이미지 캐시 구현
    NSCache를 활용해 메모리 캐시를 구현합니다.
    FileManager를 통해 Image를 Data로 변환해 저장합니다.

캐싱 방식

  1. 해당 url에 해당하는 캐시을 요청합니다.
let cachedImage = ImageCache.readCache(with: url)

2-1. 먼저 메모리 캐시에서 찾고, 없으면 디스크 캐시에서 찾아 메모리 캐시를 업데이트한 후 이미지를 리턴합니다.

public static func readCache(with imageURL: URL) -> CacheableImage? {
        let imageURLStr = imageURL.absoluteString as NSString

        if let memoryCachedImage = memoryCache.object(forKey: imageURLStr) {
            return memoryCachedImage
        } else {
            guard let diskCachedImage = diskCache.readCache(with: imageURL) else { return nil }
            memoryCache.setObject(diskCachedImage, forKey: imageURLStr)
            return diskCachedImage
        }
    }

2-2. 캐시 히트에 실패한 경우, 네트워크 요청을 통해 이미지를 가져오고 메모리 캐시와 디스크 캐시를 업데이트하고 이미지를 설정합니다.

// UIImageView+SetAsyncImage.swift
let (data, response) = try await URLSession.shared.data(from: url)
...
let cachingImage = CacheableImage(imageData: data)
ImageCache.updateCache(with: url, image: cachingImage)
...           
self.image = image

// ImageCache.swift
public static func updateCache(with imageURL: URL, image: CacheableImage) {
        let key = imageURL.absoluteString as NSString
        memoryCache.setObject(image, forKey: key)
        diskCache.updateCache(with: imageURL, image: image)
    }

✅ 리뷰 노트

빠르게 구현한거라 가독성이 좋지 않습니다🥲

@youn9k youn9k linked an issue Nov 26, 2024 that may be closed by this pull request
@youn9k youn9k self-assigned this Nov 26, 2024
@youn9k youn9k added the ✨ feat 새로운 기능 추가 label Nov 26, 2024
Copy link
Collaborator

@0Hooni 0Hooni left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

빛영규 킹영규 갓영규 킹갓제네럴엠페럴영규

LGTM 💯

Copy link
Collaborator

@hsw1920 hsw1920 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이미지 캐시 너무 좋아요!

Copy link
Member

@Kiyoung-Kim-57 Kiyoung-Kim-57 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

캐시 너무 좋습니다!

@youn9k youn9k merged commit 0e0b589 into develop Nov 27, 2024
1 check passed
@youn9k youn9k deleted the feat/#112-image-cache branch November 27, 2024 02:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ feat 새로운 기능 추가

Projects

None yet

Development

Successfully merging this pull request may close these issues.

이미지 캐시를 구현합니다.

5 participants