【发布时间】:2015-07-27 22:32:54
【问题描述】:
我希望我的应用显示用户的位置,但它不要求 WhenInUseAuthorization。我在 Info.plist 中添加了 NSLocationWhenInUseUsageDescription 键。我在 iOS 模拟器中尝试了模拟位置和实际设备。
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.authorizationStatus() == .NotDetermined {
self.locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
let userLocation = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude)
mapView.region = MKCoordinateRegionMakeWithDistance(userLocation, 100, 100)
} else {
let defaultLocation = CLLocationCoordinate2DMake(45.5017, -73.5673)
mapView.region = MKCoordinateRegionMakeWithDistance(defaultLocation, 100, 100)
}
}
}
【问题讨论】:
标签: ios swift cocoa-touch core-location