swift 获取用户当前位置并将其上传到firebase

au9on6nz  于 2023-02-07  发布在  Swift
关注(0)|答案(1)|浏览(153)

我试图获取用户在swifti中的当前位置,然后将其上传到firebase,但似乎没有任何内容被上传
我试着在代码中添加打印命令来检查我是否得到了位置,但是没有任何东西被打印到终端,下面是我的代码:

import MapKit
import FirebaseFirestore

struct Maps: View {
    @State private var location = CLLocationCoordinate2D()

    var body: some View {
        Text("Hello World")
            .onAppear {
                let manager = LocationManager()
                manager.getLocation { location in
                    self.location = location
                    print("Latitude: \(location.latitude), Longitude: \(location.longitude)")
                }
            }
    }
}

class LocationManager: NSObject, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()

    func getLocation(completion: @escaping (CLLocationCoordinate2D) -> ()) {
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        self.completion = completion
    }

    private var completion: ((CLLocationCoordinate2D) -> ())?

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }

        let db = Firestore.firestore()
        let locationRef = db.collection("locations").document()
        locationRef.setData([
            "latitude": location.coordinate.latitude,
            "longitude": location.coordinate.longitude,
            "identifier": UUID().uuidString
        ])

        locationManager.stopUpdatingLocation()
        completion?(location.coordinate)
    }
}

struct Maps_Previews: PreviewProvider {
    static var previews: some View {
        Maps()
    }
}

我在信息中添加了隐私-使用时请求,所以我不知道问题是什么,我没有收到任何错误

qhhrdooz

qhhrdooz1#

此代码

.onAppear {
    let manager = LocationManager()
    // ...
}

创建然后立即丢弃一个LocationManager,这意味着该对象在内存中的生存时间不够长,甚至无法接收对委托方法的一个回调。
manager上移为Maps的一个属性,使其与视图本身一样长时间地保留在内存中。

相关问题