如何在计时器选择器上传递参数


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 和设置选择器。但是,如何将纬度/液化参数发送到我的函数?

要使用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

确保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)
}

这正是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)
}

最新更新