Skip to content

Instantly share code, notes, and snippets.

@hehehaha0228
Created May 4, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hehehaha0228/3889cbd91b3176fe704b3c3399d86a63 to your computer and use it in GitHub Desktop.
Save hehehaha0228/3889cbd91b3176fe704b3c3399d86a63 to your computer and use it in GitHub Desktop.
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
let locationManager: CLLocationManager? = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager?.delegate = self
locationManager?.distanceFilter = kCLLocationAccuracyNearestTenMeters
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
mapView.delegate = self
mapView.showsUserLocation = true
mapView.userTrackingMode = .followWithHeading
}//viewDidLoad
override func viewDidAppear(_ animated: Bool) {
if CLLocationManager.authorizationStatus() == .notDetermined{
locationManager?.requestWhenInUseAuthorization()
locationManager?.startUpdatingLocation()
}else if CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .restricted {
DispatchQueue.main.async(){
let alertController = UIAlertController(title: "定位權限已關閉", message: "如要變更權限,請至 設定 > 隱私權 > 定位服務 開啟", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}//DispatchQueue
}else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{
locationManager?.startUpdatingLocation()
}//if
}//ViewWillAppear
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
locationManager?.stopUpdatingLocation()//離開畫面就不要再更新地理資訊了
}//viewDidDisappear
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.denied){
let alertController = UIAlertController(title: "定位權限已關閉", message: "如要取得咖啡館資訊,請至 設定 > 隱私權 > 定位服務 開啟定位功能", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}//if
}//locationManager
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment