반응형

swift 2.0 -- mapview 사용하여 현재 위치 표시하기


환경 : swift 2.0, xcode 7.0, ios 9.0


참고 : https://www.youtube.com/watch?t=2&v=qrdIL44T6FQ

         http://matthewfecher.com/app-developement/getting-gps-location-using-core-location-in-ios-8-vs-ios-7/

         https://www.veasoftware.com/tutorials/2015/5/12/current-location-in-swift-xcode-63-ios-83-tutorial




유투브 동영상 보면서, mapview 사용하여 현재 위치 표시 따라하기





** info.plist 설정

   -- 앱에서 위치정보 사용하기 위해서는 사용자 승인 얻어야 한다. 

       사용자 승인 얻기위해 info.plist 에 설정이 필요.


NSLocationAlwaysUsageDescription  -- 항상 위치정보 사용 

NSLocationWhenInUseUsageDescription -- 앱 사용중에만 위치정보 사용





** 소스


import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Location Delegate Methods
// 새로운 위치정보 발생시 실행되는 메소드
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
// 위치정보 반환
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
// MKCoordinateSpan -- 지도 scale
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta:0.01, longitudeDelta:0.01))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Errors: " + error.localizedDescription)
}
}
view raw mapview.swift hosted with ❤ by GitHub







반응형
Posted by 자유프로그램
,