Computer >> 컴퓨터 >  >> 프로그램 작성 >> IOS

Swift를 사용하여 현재 위치를 제공하기 위해 백그라운드에서 실행하는 방법은 무엇입니까?

<시간/>

신속하게 배경 위치를 얻으려면 몇 단계를 거쳐야 합니다.

info.plist 파일에 Privacy-Location always를 추가하고

사용자로부터 권한을 얻습니다.

when in use Description, Privacy – When in 사용법 설명 및 각각의 설명을 추가합니다.

그런 다음 모든 위치 관련 라이브러리 및 메서드를 사용할 수 있도록 하는 CoreLocation 프레임워크를 가져와야 합니다. 그런 다음 위치를 사용하려면 사용자의 허가를 받아야 합니다. 이를 위해 CLLocationManager 개체를 만들고 승인을 받아야 합니다.

var locationManager: CLLocationManager?
override func viewDidLoad() {
   super.viewDidLoad()
   locationManager = CLLocationManager()
   locationManager?.delegate = self
   locationManager?.requestAlwaysAuthorization()
}

이제 앱을 실행할 때 특정 모듈의 위치가 필요한 경우 사용자 권한을 요청합니다. 그 후 다음 코드를 추가하여 위치 변경 모니터링을 시작하고 위치를 업데이트할 수 있습니다.

locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.allowsBackgroundLocationUpdates = true

이 작업이 완료되면 CLLocationManagerDelegate의 didUpdateLocation 메소드를 사용하여 백그라운드에서 서버의 위치를 ​​업데이트할 수 있습니다.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   // Hit api to update location
}

이제 위치가 업데이트될 때마다 이 CLLocationManagerDelegate 메서드가 호출되고 이 내부에서 서버의 위치를 ​​업데이트하는 코드를 작성할 수 있습니다.