如何在定时器选择器上传递参数
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参数?
要使用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) }