如何在一段时间内运行一个动作?

时间:2016-12-08 17:12:49

标签: ios swift bluetooth

我正在尝试扫描5秒的蓝牙设备。但是我无法实现时间阶段。我的代码目前看起来像这样:

@IBAction func scanButton(_ sender: Any)
{
    startScanning()
    let disableScanButton = sender as? UIButton
    disableScanButton?.isEnabled = true
}

func startScanning()
{
    timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.stopScanning), userInfo: nil, repeats: true)
    print("Start Scan")
    manager?.scanForPeripherals(withServices: nil, options: nil)
    print("There are \(peripheralArray.count) no. of peripherals counted for")
    stopScanning()
}

func stopScanning()
{
    timer?.invalidate()
    print("timer stopped")
    manager?.stopScan()
    print("Scan Stopped")
}

所以我按下按钮然后扫描。但是,它似乎真的很快就能完成所有动作。我以为计时器会抓住它,但事实并非如此。有没有办法将它循环用于startScanning函数?

我看过其他人,但我似乎无法找到任何东西。那些看似非常复杂的东西。

我正在寻找一种解决方案,越简单越好。但是,如果不可能简单,那么我对人们的选择持开放态度。

1 个答案:

答案 0 :(得分:0)

您可以按照@Larme的建议实现此延迟 在这里,我用@ larme&#39的方法重写你的代码

@IBAction func scanButton(_ sender: Any)
{
    startScanning()
    let disableScanButton = sender as? UIButton
    disableScanButton?.isEnabled = true
}

func startScanning()
{
    manager?.scanForPeripherals(withServices: nil, options: nil)
    self.performSelector(#selector(stopScanning), withObject: self, afterDelay: 5)//here 5 is number of seconds after you want to execute stopScanning function, Increase the time interval or decrease it as your conviniebce


}

func stopScanning()
{
    manager?.stopScan()
    print("Scan Stopped")
    print("There are \(peripheralArray.count) no. of peripherals counted for")
}

现在您的代码不再需要NSTimer。您可以增加或减少停止扫描的时间间隔

相关问题