비전공자 개발일기

Location Information in Background Mode(iOS - Swift) 본문

SWIFT

Location Information in Background Mode(iOS - Swift)

HiroDaegu 2023. 2. 24. 23:19
728x90
SMALL

백그라운드(Background) 상태

앱의 UI가 사용자 눈에는 보이지 않지만 특정 기능을 수행하는 앱의 경우에는 계속 실행되는 상태( ex) 음악, 지도 등)

 

포그라운드(Foreground) 상태

앱의 사용자가 보고 있는 화면


Background Mode Setting


예시 코드

import UIKit
import CoreLocation

class ViewController: UIViewController {

    var locationManager: CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        requestLocationAuthorization()
        locationManager?.allowsBackgroundLocationUpdates = true
        locationManager?.startUpdatingLocation()
    }
    
    private func requestLocationAuthorization() {
        locationManager.requestAlwaysAuthorization()
    }
}

extension ViewController: CLLocationManagerDelegate {
        
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        locationStatusSwitch(with: manager)
        locationManager.startUpdatingHeading()
        locationManager.startUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print("didupdate \(location.coordinate.latitude) \(location.coordinate.longitude)")
        }
    }
    
//    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
//        print("Error \(error.localizedDescription)")
//    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        // 14.0부터
        locationStatusSwitch(with: manager)
    }
    
    func locationStatusSwitch(with locationManager: CLLocationManager) {
        var status: CLAuthorizationStatus
        if #available(iOS 14.0, *) {
            status = locationManager.authorizationStatus
        } else {
            // Fallback on earlier versions
            status = CLLocationManager.authorizationStatus()
        }
        
        switch status {
        case .notDetermined:
            break
        case .restricted:
            break
        case .denied:
            break
        case .authorizedAlways, .authorizedWhenInUse:
            locationManager.startUpdatingLocation()
            print(".authorizedAlways, .authorizedWhenInUse")
        case .authorized:
            break
        @unknown default:
            break
        }
    }
}
728x90
LIST

'SWIFT' 카테고리의 다른 글

WKWebView Component 1(Alert Event, go Back, go Forward)  (0) 2023.02.27
Device ID(UUID)  (0) 2023.02.26
Dark Mode(Light Mode) 고정하기(무시하기)  (0) 2023.02.22
Webview (Local html)  (0) 2023.02.21
QR Code Scanner Example  (0) 2023.02.20