所以我有一个名为grabUserLoc
的函数来抓取用户位置。
@objc func grabUserLoc(){
LocationService.getUserLocation { (location) in
guard let currentLocation = location else { return }
print("Latitude: \(currentLocation.coordinate.latitude)")
print("Longitude: \(currentLocation.coordinate.longitude)")
}
}
该函数使用此服务方法,该方法包含此函数。
struct LocationService {
static func getUserLocation(completion: @escaping (CLLocation?) -> Void){
print("Atttempting to get user location")
//May need location manager function
Location.getLocation(accuracy: .city, frequency:.continuous , success: { (_, location) -> (Void) in
//print("Latitide: \(location.coordinate.latitude)")
//print("Longitude: \(location.coordinate.longitude)")
return completion(location)
}) { (request, last, error) -> (Void) in
request.cancel()
print("Location monitoring failed due to an error \(error)")
return completion(nil)
}
}
}
现在我在grabUserLoc
函数中有print语句,以确保它们正常工作,因为正在抓取用户位置。但是,print语句和完成块正在运行两次,因此它运行print语句两次。在我的实施方面,我做错了吗?
顺便说一下,我正在使用名为swiftlocation的第三方位置窗格 https://github.com/malcommac/SwiftLocation
答案 0 :(得分:1)
尝试在完成之前停止位置更新,因为它可能会更新位置两次,这通常在您实现 CLLocationManager
的didLocationUpdate委托方法时发生 Location.getLocation(accuracy: .city, frequency:.continuous , success: { (_, location) -> (Void) in
//print("Latitide: \(location.coordinate.latitude)")
//print("Longitude: \(location.coordinate.longitude)")
//Stop location Update here after first call
return completion(location)
}) { (request, last, error) -> (Void) in
request.cancel()
print("Location monitoring failed due to an error \(error)")
return completion(nil)
}
使用一次Bool
包围功能 @objc func grabUserLoc(){
var once = true
LocationService.getUserLocation { (location) in
guard let currentLocation = location else {
return
}
if(once)
{
print("Latitude: \(currentLocation.coordinate.latitude)")
print("Longitude: \(currentLocation.coordinate.longitude)")
once = false;
}
}
}
答案 1 :(得分:0)
您似乎正在使用某些第三方框架来获取位置,因此我不确切知道您的代码在做什么,但是这一行:
Location.getLocation(accuracy: .city, frequency:.continuous , success:
有一个frequency
参数。也许应该将其设置为.continuous
以外的其他内容才能获得一个位置?
如果您想直接使用iOS核心位置框架,只需拨打requestLocation()
中的CLLocationManager
即可获得一个位置。