如何从后台调用locationManager didUpdateToLocation?

时间:2016-09-11 11:41:39

标签: ios swift cllocationmanager

您好我想获取用户的位置,即使应用程序在后台,然后我想将该信息上传到数据库,当用户再次运行应用程序时,它会向他显示他访问过的所有地点。所以我阅读了文章https://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial并做了作者所说的一切在功能上我添加了后台模式位置更新,我也在info.plist中设置应用程序不在后台运行到NO但我的应用程序仍然没有运行在背景可能是什么问题?

import UIKit
import CoreLocation
import MapKit



class ViewController: UIViewController, CLLocationManagerDelegate {
    var i = 0


    @IBOutlet var map: MKMapView!
    var backendless = Backendless.sharedInstance()
    lazy var locationManager: CLLocationManager = {
        let locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestAlwaysAuthorization()
        locationManager.distanceFilter = kCLDistanceFilterNone
        return locationManager
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.startUpdatingLocation()
        getLocations()
        self.map.showsUserLocation = true

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: -LocationManagerDelegate
    //func locationMana
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        let loc = MKPointAnnotation()
        loc.coordinate = newLocation.coordinate

        savelocation(loc.coordinate.longitude, latitude: loc.coordinate.latitude)
        //loc.coordinate.latitude
        //map.showAnnotations(loc, animated: true)

    }
    func savelocation(longitude: Double, latitude: Double){
        print("I work \(i)")
        i++
        let loc1 = locations()
        loc1.latitude = String(latitude)
        loc1.longitude = String(longitude)
       // print(loc1.latitude)
       // print(loc1.longitude)
        let datastore = backendless.data.of(locations.ofClass())
        var error: Fault?
        let result = datastore.save(loc1, fault: &error) as? locations
        if error == nil{
            print("data was saved")
        }else{
            print("data was not saved")
        }
    }
    func callAlert(message:String!){
        let alertController=UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        let OKButton=UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(OKButton)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    func getLocations(){
        var arr = [MKPointAnnotation]()
        //var temp: MKPointAnnotation!
        let dataStore = Backendless.sharedInstance().data.of(locations.ofClass())
        var error: Fault?
        let result = dataStore.findFault(&error)
        if error == nil{
            let locs = result.getCurrentPage()
            //     print(cities)
            let locs1 = locs as! [locations]
            if locs1.count - 1 >= 0{
                for index in 0...locs1.count - 1{
                    let temp = MKPointAnnotation()
                    temp.coordinate.latitude = Double(locs1[index].latitude!)!
                    temp.coordinate.longitude = Double(locs1[index].longitude!)!
                    arr.append(temp)
                }
                self.map.addAnnotations(arr)
            }
        }else{
            self.callAlert("There is an error retrieving data")
        }

    }


}

我也尝试过更改appdelegate applicationDidEnterBackground方法,但我不知道如何手动调用该方法。有帮助吗?谢谢。 :) P.s.s.我知道这是非法的,应用程序应该自己调用它,但我不知道如何以不同的方式做到这一点

1 个答案:

答案 0 :(得分:0)

您似乎已将locationManager设置为懒惰变量,并且我假设它已在此次调用中初始化:locationManager.startUpdatingLocation()。您应该实现此方法来启动更新:

func locationManager(manager: CLLocationManager, 
                     didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status:
    case .AuthorizedAlways:
        manager.startUpdatingLocation()
    default:
        break
}

注意:这至少会让您知道您已正确授权您的应用使用该用户的位置。您仍然需要使用您的lazy var locationManager属性来实例化它。我建议您使用常规属性,并在locationManager中设置viewDidLoad