【问题标题】:In widget using swiftui how to get current location? [duplicate]在使用 swiftui 的小部件中如何获取当前位置? [复制]
【发布时间】:2023-03-18 09:35:01
【问题描述】:

如何在小部件中获取用户当前位置?我正在使用 swiftUI。

【问题讨论】:

    标签: swiftui widget core-location


    【解决方案1】:
    class WidgetLocationManager: NSObject, CLLocationManagerDelegate {
        var locationManager: CLLocationManager? 
        private var handler: ((CLLocation) -> Void)?
    
        override init() {
            super.init()
            DispatchQueue.main.async {
                self.locationManager = CLLocationManager()
                self.locationManager!.delegate = self
                if self.locationManager!.authorizationStatus == .notDetermined {
                    self.locationManager!.requestWhenInUseAuthorization()
                }
            }
        }
        
        func fetchLocation(handler: @escaping (CLLocation) -> Void) {
            self.handler = handler
            self.locationManager!.requestLocation()
        }
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            self.handler!(locations.last!)
        }
        
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print(error)
        }
    }
    

    打电话

    var widgetLocationManager = WidgetLocationManager()
    
    func getTimeline(for configuration: SelectPlaceIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
        widgetLocationManager.fetchLocation(handler: { location in
            print(location)
            .......
        })
    }
    

    【讨论】:

    • 我忍不住又靠近了一步
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多