我的另外一篇博客:

iOS swift 在app被杀死的情况下获取(上报)位置 后台 定位 本人实测有效

// 第一步 引入api
import CoreLocation

public class LocationManager: NSObject{
    // 单例方法
    static let sharedInstance: LocationManager = {
        let instance = LocationManager()
        // setup code
        return instance
    }()

    var locationManager: CLLocationManager?
    
    // 调用此方法初始化定位功能
    public func initialize(){
        if (self.locationManager == nil) {
           self.locationManager = CLLocationManager()
           // 设置代理
           self.locationManager?.delegate = self
           // 设置定位精度
           locationManager?.desiredAccuracy = kCLLocationAccuracyBest
           // 设置变动幅度
//           locationManager?.distanceFilter = 5.0
            // 允许后台持续使用定位功能
           locationManager?.allowsBackgroundLocationUpdates = true
            // 进入后台后不停止
           self.locationManager?.pausesLocationUpdatesAutomatically = false
        }
    }
    
    // 开始尝试获取定位
    public func startRequestLocation() {
        print(#function)
        if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined) {
            // 没有获取到权限,再次请求授权
            self.locationManager?.requestWhenInUseAuthorization()
            print("shenqing")
        } else {
            print("开始")
            locationManager?.startUpdatingLocation()
        }
    }

}





// 实现代理
extension LocationManager: CLLocationManagerDelegate {
    // 代理方法,位置更新时回调
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(#function)
        let location = locations.last ?? CLLocation.init()
        let coordinate = location.coordinate
        let latitude = coordinate.latitude;
        let longitude = coordinate.longitude;
        print(String(latitude)+"s")
        print(longitude)
        sendLocation(latitude: String(latitude), longitude: String(longitude))
        // TODO... 实现自己的业务
        // 注意,这里获取到的是标准坐标。WGS-84标准
    }
    
    // 代理方法,当定位授权更新时回调
    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print(#function)
        print(status.rawValue)
        // CLAuthorizationStatus
        // .notDetermined   用户还没有选择授权
        // .restricted   应用没有授权用户定位
        // .denied 用户禁止定位
        // .authorizedAlways 用户授权一直可以获取定位
        // .authorizedWhenInUse 用户授权使用期间获取定位
        // TODO...
        if status == .notDetermined {
//            self.startRequestLocation()
        } else if (status == .restricted) {
            // 受限制,尝试提示然后进入设置页面进行处理
            
        } else if (status == .denied) {
            // 被拒绝,尝试提示然后进入设置页面进行处理
            
        }
        self.startRequestLocation()
    }

    // 当获取定位出错时调用
    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        // 这里应该停止调用api
        self.locationManager?.stopUpdatingLocation()
    }
    
    func sendLocation(latitude:String,longitude:String){
        
        let dict:Dictionary = ["latitude":latitude,"longitude":longitude]
        let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
        var request = URLRequest(url: URL(string: "http://cloud.bmob.cn/fdabdcf0ee5cac9a/sendLocation")!)
        request.httpMethod = "POST"
        request.httpBody = data
        //记得要设置Content-Type为application/json,不然可能发生错误
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error.debugDescription)
            }else{
                print(String(data:data!, encoding: String.Encoding.utf8))
                if let any = try?JSONSerialization.jsonObject(with: data!, options: .allowFragments){
                    let dict : Dictionary = any as! Dictionary<String, Any>
                    print(dict)
                }
               
            }
           
        }
        task.resume()

    }

}

参考博客:
IOS(swift)获取用户定位及坐标转换

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐