GeoFire + Swift + Firebase:保存当前位置

时间:2017-11-22 15:20:30

标签: swift firebase location geofire

这是有效的:

geoFire.setLocation(CLLocation(latitude: 37.7853889, longitude: -122.4056973), 
   forKey: "firebase-hq") { (error) in
  if (error != nil) {
    println("An error occured: \(error)")
  } else {
    println("Saved location successfully!")
  }
}

但是如何将当前位置坐标发送到Firebase?像这样?但是currentLocation不起作用。

geoFire!.setLocation(currentLocation, forKey: "firebase-hq") { (error) in
                                if (error != nil) {
                                    print("An error occured: \(error)")
                                } else {
                                    print("Saved location successfully!")
                                }

1 个答案:

答案 0 :(得分:0)

除非完全有必要,否则我建议不要使用GeoFire,而是使用Apple的内置API。首先,打开info.plist文件作为源代码,并将以下内容添加到文件

<key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location? 
</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Will you allow this app to always know your current location? 
</string>

然后将此代码添加到新的viewcontroller:

import UIKit
import CoreLocation


class SearchViewController: UIViewController, CLLocationManagerDelegate {

var locationManager:CLLocationManager!



override func viewDidLoad() {
    super.viewDidLoad()
    // 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.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    determineMyCurrentLocation()
}


func determineMyCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
        //locationManager.startUpdatingHeading()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation

    // Call stopUpdatingLocation() to stop listening for location updates,
    // other wise this function will be called every time when user location changes.

    // manager.stopUpdatingLocation()

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")



}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
    print("Error \(error)")
}
}

这将打印您的经度和经度作为模拟器中的默认当前位置,如旧金山某处。要更改此设置,请进入模拟器并进入调试菜单,然后单击位置,当前位置并输入您首选的新值。