반응형
CLLocationManager
위치 권한 설정
Info.plist
Privacy - Location When In Use Usage Description : 앱 사용중일 때만 GPS 사용 (for use in foreground)
Privacy - Location Always and When In Use Usage Description : 위치 정보 항상 사용 (앱 사용 안할 때도)
위도 경도 가져오기
import UIKit
class ViewController: UIViewController {
var locationManager: CLLocationManager!
var currentLocation: String?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
//위치추적권한요청 when in foreground
self.locationManager.requestWhenInUseAuthorization()
//베터리에 맞게 권장되는 최적의 정확도
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
//위도, 경도 가져오기
currentLocation = "\(locValue.latitude), \(locValue.longitude)"
}
}
참고 : AdvancedSwift - Get User Location In Swift with CLLocationManager,
주소 가져오기
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager.init()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
let geocoder = CLGeocoder.init()
let location = self.locationManager.location
if location != nil {
geocoder.reverseGeocodeLocation(location!) { (placemarks, error) in
if error != nil {
return
}
if let placemark = placemarks?.first {
var address = ""
if let administrativeArea = placemark.administrativeArea {
address = "\(address) \(administrativeArea) "
print(administrativeArea) //서울특별시
}
if let locality = placemark.locality {
address = "\(address) \(locality) "
print(locality) //광진구
}
if let thoroughfare = placemark.thoroughfare {
address = "\(address) \(thoroughfare) "
print(thoroughfare) //중곡동
}
if let subThoroughfare = placemark.subThoroughfare {
address = "\(address) \(subThoroughfare)"
print(subThoroughfare) //272-13
}
}
print(address) //서울특별시 광진구 중곡동 272-13
}
}
}
}
728x90
반응형
'Swift iOS 앱 개발 > Swift' 카테고리의 다른 글
[Swift iOS] UIComponents (0) | 2021.11.08 |
---|---|
[Swift iOS] UICollectionView scroll to top / bottom (0) | 2021.10.13 |
[Swift iOS] WKNavigationDelegate 하이브리드 앱에서 webview 탐색 및 관리 (0) | 2021.10.05 |
[Swift iOS] Convert number into money format with a comma (feat. NumberFormatter 숫자 콤마 표시) (0) | 2021.09.30 |
[Swift iOS] webview 로딩 완료 감지 (feat. WKNavigationDelegate) (0) | 2021.09.27 |