swift - 如何将当前用户位置保存为默认值?
问题描述
我试图让用户选择保存他们当前的位置。我使用默认值来保存它,我发现了如何获取用户位置。但我不确定如何结合这两个任务。所以这是我的问题:
如何让我的功能调用用户位置,以便保存?
@IBAction func addLocation(_ sender: Any) {
// CALL LOCATION MANAGER TO GET LOCATION IN LAT AND LONG
self.saveDefaults()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func saveDefaults()
{
UserDefaults.standard.set(self.pickers, forKey: "pickers")
print("SAVED PICKERS: \(pickers)")
}
这是我最近的尝试,但我不知道为什么我的 struct (lat: ,long:) 没有接受输入
@IBAction func addLocation(_ sender: Any) {
var locations: [CLLocation]
let manager: CLLocationManager
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)")
self.pickers.append(pickerStruct(lat: userLocation.coordinate.latitude, long: userLocation.coordinate.longitude))
self.saveDefaults()
}
解决方案
@IBAction func addLocation(_ sender: Any) {
locationManager.startUpdatingLocation() //This will call the delegate method below where you can save the location
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard locations.count > 0 else {
return
}
guard let location = locations.last else {
return
}
locationManager.stopUpdatingLocation() //Stop location updates after getting the location and save that location as below
let encodedLocation = NSKeyedArchiver.archivedData(withRootObject: location)
UserDefaults.standard.set(encodedLocation, forKey: "savedLocation")
}
从 UserDefaults 取回位置:
let previousLocationEncoded = UserDefaults.standard.object(forKey: "savedLocation") as? Data
let previousLocationDecoded = NSKeyedUnarchiver.unarchiveObject(with: previousLocationEncoded!) as! CLLocation
推荐阅读
- javascript - 在Javascript中将char转换为字符串
- ros - 在 Ubuntu 20.04 中找不到 ROS 包
- javascript - 响应中“Access-Control-Allow-Origin”标头的值不能是 azure function 和 javascript 中的通配符“*”
- javascript - 为什么我的 javascript 函数没有运行?
- node.js - 如何解决此类型错误:super 表达式必须为 null 或函数,而不是未定义
- html - 节点快递中的间歇性响应“不允许未经身份验证的请求”
- java - 如何在 Z3 java API 中定义一个函数?
- javascript - 如何在 javascript 中拆分此字符串?
- c - 为什么要区分 BSS 和 COMMON 部分?
- swift - 如何从 macOS APP 在 LaunchAgents 中创建守护进程?