[swift] Swift FirebaseUI를 사용하여 위치 기반 추천 기능 구현하기

Firebase는 클라우드 기반의 모바일 및 웹 애플리케이션 개발을 위한 플랫폼으로, 사용자 인증, 데이터베이스, 스토리지 등 다양한 기능을 제공합니다. FirebaseUI는 Firebase를 iOS 앱에서 손쉽게 사용할 수 있도록 도와주는 라이브러리입니다.

이번 글에서는 Swift FirebaseUI를 사용하여 위치 기반 추천 기능을 구현하는 방법에 대해 알아보겠습니다.

1. Firebase 설정하기

먼저 Firebase 콘솔에서 프로젝트를 생성하고, 해당 프로젝트에 iOS 앱을 추가해야 합니다. Firebase가 프로젝트 설정 파일을 생성해주기 때문에, Firebase가 연동된 iOS 앱에서 해당 설정 파일을 사용할 수 있습니다.

Firebase 콘솔에서 생성한 프로젝트에 iOS 앱을 추가한 후, 프로젝트 설정 파일(GoogleService-Info.plist)을 다운로드하여 프로젝트에 추가합니다.

2. FirebaseUI 설치하기

FirebaseUI는 CocoaPods를 통해 설치할 수 있습니다. Podfile에 다음과 같이 FirebaseUI를 추가합니다.

pod 'FirebaseUI', '~> 9.0'

설치를 완료한 후, import FirebaseUI를 통해 FirebaseUI를 임포트합니다.

3. 위치 정보 설정하기

이제 위치 정보를 사용하기 위해 iOS 앱에서 위치 접근 권한을 설정해야 합니다. Info.plist 파일에 다음 항목을 추가합니다.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Your location is used to provide personalized recommendations.</string>

또한, iOS 14부터는 앱이 위치 데이터를 수집하는 용도를 명시적으로 설명해야 합니다. 따라서 Info.plist 파일에 다음 항목을 추가합니다.

<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Your location is used to provide personalized recommendations.</string>
</dict>

4. 위치 기반 추천 기능 구현하기

FirebaseUI를 사용하여 위치 기반 추천 기능을 구현하는 방법은 간단합니다. 먼저, FirebaseUI의 FUIFirestoreCollectionViewDataSource 클래스를 사용하여 Firestore 데이터를 가져오는 작업을 수행합니다.

import UIKit
import Firebase
import FirebaseUI

class ViewController: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!
    
    var dataSource: FUIFirestoreCollectionViewDataSource!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let query = Firestore.firestore().collection("recommendations").order(by: "distance")
        let options = FUICollectionViewDataSourceOptions()
        options.paginationLimit = 10
        
        self.dataSource = collectionView.firestoreDataSource(query: query, options: options, reuseIdentifier: "cell") { collectionView, indexPath, document in
            // 데이터를 사용하여 셀을 구성하는 로직을 작성합니다.
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
            let recommendation = document.data() as [String: Any]
            cell.title.text = recommendation["title"] as? String
            cell.description.text = recommendation["description"] as? String
            
            return cell
        }
    }
}

위 코드에서 recommendations는 Firestore 컬렉션의 이름입니다. 데이터를 가져올 때 order(by: "distance")를 사용하여 거리 기준으로 정렬할 수 있습니다. 또한, FUICollectionViewDataSourceOptions를 사용하여 페이징(limit)을 설정할 수 있습니다.

위치 기반 추천 기능을 구현하기 위해서는 사용자의 현재 위치를 가져와야 합니다. 이를 위해 CLLocationManager를 사용할 수 있습니다.

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        
        if CLLocationManager.locationServicesEnabled() {
            locationManager.requestLocation()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            // 위치 정보를 사용하여 Firebase 쿼리를 업데이트하는 작업을 수행합니다.
            let latitude = location.coordinate.latitude
            let longitude = location.coordinate.longitude
            
            let geoPoint = GeoPoint(latitude: latitude, longitude: longitude)
            self.dataSource.updateQuery {
                $0.whereField("location", isNearTo: geoPoint, within: 10) // 10km 내의 추천 정보만 가져옵니다.
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        // 위치 정보를 가져오지 못한 경우, 기본 쿼리를 사용하여 데이터를 가져옵니다.
        self.dataSource.updateQuery {
            $0.limit(to: 10)
        }
    }
}

위 코드에서는 위치 정보를 가져온 후, Firebase의 쿼리를 업데이트하는 작업을 수행합니다. 사용자의 현재 위치를 기반으로 10km 내의 추천 정보만 가져오도록 쿼리를 업데이트합니다.

이제 위치 기반 추천 기능의 구현이 완료되었습니다.

결론

이번 글에서는 Swift FirebaseUI를 사용하여 위치 기반 추천 기능을 구현하는 방법을 알아보았습니다. FirebaseUI를 사용하면 Firebase의 다양한 기능을 쉽게 iOS 앱에서 사용할 수 있습니다. 위치 기반 추천 기능을 구현하기 위해 Firebase의 Firestore와 CLLocationManager를 함께 활용하는 방법을 살펴보았습니다.