swiftui - 在使用 swiftui 的小部件中如何获取当前位置?
问题描述
如何在小部件中获取用户当前位置?我正在使用 swiftUI。
解决方案
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)
.......
})
}
推荐阅读
- materialize - 在浮动按钮中实现 CSS 图标定位
- ios - 使用 Swift 4,如何获取本地存储的图像?
- ios - 使用 Objective-C 检索 SSL 证书的信息
- php - 将值返回给 laravel 中的许多视图
- java - android:如何将字符串转换为日期
- java - 此客户端应用程序的回调 URL 未获批准
- javascript - 在区间函数中反应 setAttribute
- javascript - 使用jspdf时转换/规范化特殊字符
- python - How to get every n-word from a string and save the new sentence in the variable
- php - Laravel 5 multi-level relations with pivot table