I am trying to scan for bluetooth devices for 5s. However I am unable to implement the time phase. My code currently looks like this:
@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")
}
So I press the button and then it scans. However, it just seems to jump through all the actions really quickly. I thought the timer would hold it, but it does not. Is there someway to loop it for the startScanning function?
I have looked at other people, but I can't seem to find anything. And those that do seem very complex.
I am looking for a solution, simpler the better. However, if simple is not possible then I am open to whatever options people have.
You could achieve this delay as suggested by @Larme Here I am rewriting your code with @larme's approach
@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")
}
Now NSTimer is not required anymore with your code.and you may increase or decrease the time interval to stop your scanning
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.