[swift] IGListDiffKit과 함께하는 바코드 스캐너 구현

이 포스트에서는 IGListDiffKit 라이브러리를 사용하여 바코드 스캐너를 구현하는 방법을 알아보겠습니다. IGListDiffKit는 UICollectionView나 UITableView에서 데이터 변경을 감지하고 업데이트하는 데 도움을 주는 강력한 도구입니다.

IGListDiffKit 소개

IGListDiffKit은 Instagram에서 개발한 오픈 소스 프레임워크로, 수많은 아이템들의 변경을 효율적으로 처리할 수 있습니다. 이를 통해 사용자 인터페이스를 더욱 부드럽게 업데이트할 수 있습니다.

바코드 스캐너 구현하기

  1. 프로젝트에 IGListDiffKit 추가하기:

    import IGListDiffKit
    
  2. UICollectionViewDelegate와 UICollectionViewDataSource를 채택한 후, IGListDiffable 프로토콜을 구현합니다:

    class BarcodeScannerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
        // ...
    }
    
  3. IGListAdapter를 생성하고 이를 UICollectionView와 연결합니다:

    class BarcodeScannerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
        private var collectionView: UICollectionView!
        private var adapter: IGListAdapter!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // UICollectionView 초기화
    
            // IGListAdapter 초기화
    
            // ...
    
            adapter.collectionView = collectionView
            adapter.dataSource = self
        }
    }
    
  4. 데이터 소스를 구현합니다:

    class BarcodeScannerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
        // ...
    
        private var items: [BarcodeItem] = []
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // ...
    
            items = fetchBarcodeItems()
            adapter.performUpdates(animated: true)
        }
    
        func fetchBarcodeItems() -> [BarcodeItem] {
            // 바코드 아이템들을 가져오는 로직 작성
        }
    
        // ...
    }
    
  5. IGListDiffable 프로토콜을 구현한 데이터 모델을 생성합니다:

    struct BarcodeItem: Codable, Hashable, Equatable {
        let barcode: String
    
        func diffIdentifier() -> NSObjectProtocol {
            return barcode as NSObjectProtocol
        }
    
        func isEqual(toDiffableObject object: IGListDiffable?) -> Bool {
            guard let object = object as? BarcodeItem else { return false }
            return self == object
        }
    }
    
  6. 필요한 경우 아이템의 변경사항을 감지하고 업데이트하도록 구현합니다:

    class BarcodeScannerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
        // ...
    
        func updateBarcodeItems() {
            let newItems = fetchBarcodeItems()
            let diffResult = IGListDiff(oldArray: items, newArray: newItems, option: .equality)
            items = newItems
            adapter.performUpdates(animated: true, completion: nil)
        }
    
        // ...
    }
    

결론

IGListDiffKit은 바코드 스캐너와 같은 대규모의 데이터 업데이트를 효율적으로 처리하는 데 도움을 줍니다. IGListDiffKit과 함께하면 사용자 인터페이스의 성능을 향상시킬 수 있습니다.

참고 자료