iOS7.0以上 完整定位

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,收工

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。