菜鸟教程小白 发表于 2022-12-11 17:29:20

ios - 如何从后台调用 locationManager didUpdateToLocation?


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

<pre><code>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(&#34;I work \(i)&#34;)
      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: &amp;error) as? locations
      if error == nil{
            print(&#34;data was saved&#34;)
      }else{
            print(&#34;data was not saved&#34;)
      }
    }
    func callAlert(message:String!){
      let alertController=UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
      let OKButton=UIAlertAction(title: &#34;OK&#34;, style: .Default, handler: nil)
      alertController.addAction(OKButton)
      self.presentViewController(alertController, animated: true, completion: nil)
    }
    func getLocations(){
      var arr = ()
      //var temp: MKPointAnnotation!
      let dataStore = Backendless.sharedInstance().data.of(locations.ofClass())
      var error: Fault?
      let result = dataStore.findFault(&amp;error)
      if error == nil{
            let locs = result.getCurrentPage()
            //   print(cities)
            let locs1 = locs as!
            if locs1.count - 1 &gt;= 0{
                for index in 0...locs1.count - 1{
                  let temp = MKPointAnnotation()
                  temp.coordinate.latitude = Double(locs1.latitude!)!
                  temp.coordinate.longitude = Double(locs1.longitude!)!
                  arr.append(temp)
                }
                self.map.addAnnotations(arr)
            }
      }else{
            self.callAlert(&#34;There is an error retrieving data&#34;)
      }

    }


}
</code></pre>

<p>我也尝试更改 appdelegate applicationDidEnterBackground 方法,但我不知道如何手动调用该方法。有什么帮助吗?谢谢。 :)我知道这是非法的,应用程序应该自己调用它,但我不知道如何以不同的方式做到这一点</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您似乎已将您的 <code>locationManager</code> 设置为惰性 var,我假设它在此调用时被初始化:<code>locationManager.startUpdatingLocation()</code>。你应该实现这个方法来开始更新:</p>

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

<p><strong>注意:</strong>这至少会让您知道您已正确授权您的应用使用用户的位置。你仍然需要一些东西来使用你的 <code>lazy var locationManager</code> 属性来实例化它。我建议改用常规属性,并在 <code>viewDidLoad</code> 中设置您的 <code>locationManager</code>。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何从后台调用 locationManager didUpdateToLocation?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39435696/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39435696/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何从后台调用 locationManager didUpdateToLocation?