func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let mostRecentLocation = locations.last else {
return
}
print(mostRecentLocation.coordinate.latitude)
print(mostRecentLocation.coordinate.longitude)
Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(StartTestVC.sendDataToServer), userInfo: nil, repeats: true)
}
func sendDataToServer (latitude: Double, longitude: Double) {
SFUserManager.shared.uploadPULocation(latitude, longitude:longitude)
}
我希望每1分钟向服务器发送一次数据。我正在使用Timer.scheduledTimer和设置选择器。但是我如何向我的函数发送lat / lng参数?
答案 0 :(得分:4)
要使用Timer
发送数据,您可以使用userInfo
参数传递数据。
以下是您可以通过它调用选择器方法的示例,您可以将位置坐标传递给它。
Timer.scheduledTimer(timeInterval: 0.5, target: self, selector:#selector(iGotCall(sender:)), userInfo: ["Name": "i am iOS guy"], repeats:true)
根据以下内容处理userInfo
您需要执行的操作。
func iGotCall(sender: Timer) {
print((sender.userInfo)!)
}
对于您的情况,请确保经常调用didUpdateLocations
。
答案 1 :(得分:1)
确保你的sendDataToServer
始终上传最新坐标而不输入函数坐标作为输入参数的一种方法是将值存储在范围内,该范围可由函数访问并使用这些函数内部的值。
假设您将mostRecentLocation
作为类属性,则可以使用下面的代码
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let mostRecentLocation = locations.last else {
return
}
self.mostRecentLocation = mostRecentLocation
Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(StartTestVC.sendDataToServer), userInfo: nil, repeats: true)
}
func sendDataToServer() {
SFUserManager.shared.uploadPULocation(self.mostRecentLocation.coordinate.latitude, longitude:self.mostRecentLocation.coordinate.longitude)
}
答案 2 :(得分:0)
这正是userInfo
参数的用途:
struct SendDataToServerData { //TODO: give me a better name
let lastLocation: CLLocation
// Add other stuff if necessary
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let mostRecentLocation = locations.last else { return }
print(mostRecentLocation.coordinate.latitude)
print(mostRecentLocation.coordinate.longitude)
Timer.scheduledTimer(
timeInterval: 60.0,
target: self,
selector: #selector(StartTestVC.sendDataToServer(timer:)),
userInfo: SendDataToServerData(mostRecentLocation: mostRecentLocation),
repeats: true
)
}
// Only to be called by the timer
func sendDataToServerTimerFunc(timer: Timer) {
let mostRecentLocation = timer.userInfo as! SendDataToServerData
self.sendDataToServer(
latitude: mostRecentLocation.latitude
longitude: mostRecentLocation.longitude
)
}
// Call this function for all other uses
func sendDataToServer(latitude: Double, longitude: Double) {
SFUserManager.shared.uploadPULocation(latitude, longitude:longitude)
}