标签:
1.导入2个系统框架
import CoreLocation
import MapKit
2.在plist里面添加字段
NSLocationAlwaysUsageDescription 或者 NSLocationWhenInUseUsageDescription 或者都添加
3.在func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.startUpdatingLocation()
}else {
UIAlertView(title: "定位服务无法使用,请开启手机定位服务.", message: nil, delegate: nil, cancelButtonTitle: "知道了").show()
}
4.func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {//授权检察
preAuthorStatus = status
switch status {
case .NotDetermined://未选择
if manager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
manager.requestAlwaysAuthorization()
}
case .Restricted://受限
showAlert("定位服务无法使用,请开启手机定位服务.", nil, nil, byVC: nil, nil)
case .Denied://拒绝
let actions = [
UIAlertAction(title: "关闭", style: .Cancel, handler: nil),
UIAlertAction(title: "前去设置", style: .Default, handler: { (action: UIAlertAction!) -> Void in
let url = NSURL(string: UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
})
]
showAlert("程序定位服务未开启", "您需要去设置界面启用我们App定位服务", actions, byVC: nil, nil)
default:
break
}
}
5.func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.startUpdatingLocation()
if CLLocationManager.authorizationStatus() == preAuthorStatus && preAuthorStatus == .Denied
{
let actions = [
UIAlertAction(title: "关闭", style: .Cancel, handler: nil),
UIAlertAction(title: "前去设置", style: .Default, handler: { (action: UIAlertAction!) -> Void in
let url = NSURL(string: UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
})
]
showAlert("程序定位服务未开启", "您需要去设置界面启用我们App定位服务", actions, byVC: nil, nil)
}
}else {
manager.delegate = nil
manager.stopUpdatingLocation()
showAlert("定位服务无法使用,请开启手机定位服务.", nil, [UIAlertAction(title: "知道了", style: .Cancel, handler: nil)], byVC: nil, nil)
}
}
OK,收工
标签:
原文地址:http://blog.csdn.net/gxp1032901/article/details/44339813