[swift] Swift SkeletonView 위치 기반 서비스 구현

Swift Logo

이번에는 Swift 언어를 사용하여 SkeletonView를 이용한 위치 기반 서비스를 구현하는 방법에 대해 알아보겠습니다. SkeletonView는 사용자가 서비스 실행 도중에 데이터를 로딩하는 동안 보여지는 로딩 화면을 제공합니다.

SkeletonView 설정하기

먼저, SkeletonView를 사용하기 위해서는 프로젝트에 해당 라이브러리를 추가해야 합니다.

pod 'SkeletonView'

위의 코드를 Podfile에 추가하고, 터미널에서 pod install 명령어를 실행하여 해당 라이브러리를 설치합니다.

위치 기반 서비스 구현하기

  1. 사용자의 위치 정보를 가져오는 LocationManager 클래스를 생성합니다.
import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
    static let shared = LocationManager()
    
    private let locationManager = CLLocationManager()
    
    var currentLocation: CLLocation?
    
    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.requestWhenInUseAuthorization()
    }
    
    func startUpdatingLocation() {
        locationManager.startUpdatingLocation()
    }
    
    func stopUpdatingLocation() {
        locationManager.stopUpdatingLocation()
    }
    
    // CLLocationManagerDelegate methods
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        currentLocation = location
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("LocationManager error: \(error.localizedDescription)")
    }
}
  1. ViewController에서 위치 기반 서비스를 구현합니다.
import UIKit
import SkeletonView

class LocationBasedViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    
    var locations: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.isSkeletonable = true
        tableView.showSkeleton()
        
        LocationManager.shared.startUpdatingLocation()
        // 서버로부터 위치 기반 데이터를 가져와서 locations 배열에 저장
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            // 서버 통신이 완료되면
            self.locations = // 서버로부터 받은 위치 데이터 배열
            self.tableView.reloadData()
            self.tableView.hideSkeleton()
        }
    }
}

extension LocationBasedViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        locations.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell", for: indexPath)
        cell.textLabel?.text = locations[indexPath.row]
        return cell
    }
}

위의 코드에서는 LocationManager를 사용하여 사용자의 위치를 가져오고, 서버로부터 위치 기반 데이터를 받아와서 UITableView에 표시합니다. 서버의 응답이 오기 전까지는 SkeletonView를 사용하여 로딩 화면을 보여줍니다. 응답이 완료되면 UITableView를 업데이트하고 SkeletonView를 숨깁니다.

이제 위의 코드를 참고하여 SkeletonView를 이용한 위치 기반 서비스를 구현해보세요!

참고 자료