Created
May 4, 2018 15:10
-
-
Save hehehaha0228/3889cbd91b3176fe704b3c3399d86a63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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