iOS/코드조각

[iOS, Swift] MapKit 사용하여 현재 위치 나타내기

검은참깨두유vm 2023. 2. 16. 00:01
반응형

iOS 16.1, Xcode 14.1, Swift 5, UIKit 환경에서 진행했습니다.

 

스토리보드에서 MapKit을 화면이 꽉차도록 설정합니다.

 

Info.plist 파일에 위와 같이 3가지 설정을 해줍니다.

 

 

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController {
    
    @IBOutlet weak var mapView: MKMapView!
    
    var locationManager: CLLocationManager = CLLocationManager()
    var currentLocation: CLLocation!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        mapView.mapType = .standard
        
        mapView.showsUserLocation = true
        mapView.setUserTrackingMode(.follow, animated: true)
        
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges()
        
        self.currentLocation = locationManager.location
    }
    
}

extension ViewController: CLLocationManagerDelegate, MKMapViewDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationManager = manager
        if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            currentLocation = locationManager.location
        }
    }
}
반응형