사용자 위치 실시간 Swift 5 가져오기

7039 단어 programmingiosswift
앱이 백그라운드 모드로 전환될 때 업데이트를 받는 것을 포함하여 CoreLocation을 사용하여 실시간으로 사용자 위치를 얻는 방법을 배우게 됩니다.

Xcode가 이미 설치되어 있고 Xcode에서 프로젝트를 생성하는 방법을 알고 있다고 가정합니다.



1단계: LatLngLabel 설정



현재 위치의 위도 및 경도 값을 표시하는 latLngLabel이라는 UILabel을 만들어 보겠습니다.

import UIKit

class ViewController: UIViewController{

    private let latLngLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = .systemFill
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 26)
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()        
        latLngLabel.frame = CGRect(x: 20, y: view.bounds.height / 2 - 50, width: view.bounds.width - 40, height: 100)
        view.addSubview(latLngLabel)
    }
}


LatLngUILabel은 일부 속성으로 초기화되고 viewDidLoad() 내부의 프레임 속성을 사용하여 위치(x, y) 및 치수(너비, 높이)가 할당됩니다.

I could use Auto Layout but I used fixed values to position it on view for simplity sake.



마지막으로 addSubView() 메서드를 사용하여 보기 개체에 추가하면 앱 보기가 다음과 같이 표시됩니다.



Info.plist에 개인 정보 속성 추가



따라서 프로젝트 탐색기 → info.plist로 이동하여 키 열의 오른쪽 상단에 있는 + 기호를 누르고 선택합니다.

  • 개인 정보 보호 – 위치 항상 및 사용 중 사용 설명 및
  • 프라이버시 – 사용 중 위치 사용 설명

  • 이러한 속성의 값은 실제로 권한 경고 보기에서 사용자에게 표시됩니다.

    예: "효율적인 목적을 위해 귀하의 위치가 관리자에게 공유됩니다."



    핵심 위치



    보시다시피 상단에 CoreLocation을 가져오고 클래스 정의 내부에 CLLocationManager 유형으로 선택적인 locationManager를 선언했습니다.

    import UIKit
    import CoreLocation
    
    class ViewController: UIViewController{
        private var locationManager:CLLocationManager?
        ...
    
        override func viewDidLoad() {
            super.viewDidLoad()
            ...
            getUserLocation()
        }
    
       func getUserLocation() {
            locationManager = CLLocationManager()
            locationManager?.requestAlwaysAuthorization()
            locationManager?.startUpdatingLocation()
        }
    }
    


    그런 다음 getUserLocation() 함수 내에서 CLLocationManager를 인스턴스화합니다.

    requestAlwaysAuthorization() 메서드는 실제로 권한 경고 보기를 화면에 표시하고 있습니다.



    사용자가 한 번 허용을 선택하여 권한을 부여하면 startUpdatingLocation() 메서드는 실제로 장치 GPS에서 위치 데이터를 가져옵니다.

    그리고 상태 표시줄의 위치 아이콘에 채워진 색상이 있는 것을 볼 수 있습니다.



    CLLocationManagerDelegate()



    실제 사용자 위치 데이터에 액세스하려면 CLLocationManagerDelegate의 일부인 didUpdateLocations() 메서드를 사용해야 합니다.

    따라서 클래스 정의에 CLLocationManagerDelegate를 추가하십시오.

    Continue Reading...

    좋은 웹페이지 즐겨찾기