Navaron Bracke

refactor toggle torch on MacOS

@@ -274,12 +274,10 @@ public class MobileScannerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, @@ -274,12 +274,10 @@ public class MobileScannerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler,
274 return 274 return
275 } 275 }
276 276
277 - // Enable the torch if parameter is set and torch is available  
278 - if (device.hasTorch) { 277 + // Turn on the torch if requested.
  278 + if (torch) {
279 do { 279 do {
280 - try device.lockForConfiguration()  
281 - device.torchMode = torch ? .on : .off  
282 - device.unlockForConfiguration() 280 + toggleTorchInternal(.on)
283 } catch { 281 } catch {
284 result(FlutterError(code: error.localizedDescription, message: nil, details: nil)) 282 result(FlutterError(code: error.localizedDescription, message: nil, details: nil))
285 return 283 return
@@ -319,22 +317,25 @@ public class MobileScannerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, @@ -319,22 +317,25 @@ public class MobileScannerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler,
319 let answer: [String : Any?] = ["textureId": textureId, "size": size, "torchable": device.hasTorch] 317 let answer: [String : Any?] = ["textureId": textureId, "size": size, "torchable": device.hasTorch]
320 result(answer) 318 result(answer)
321 } 319 }
322 -  
323 - func toggleTorch(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { 320 +
  321 + // TODO: this method should be removed when iOS and MacOS share their implementation.
  322 + private func toggleTorchInternal(_ torch: AVCaptureDevice.TorchMode) throws {
324 if (device == nil || !device.hasTorch || !device.isTorchAvailable) { 323 if (device == nil || !device.hasTorch || !device.isTorchAvailable) {
325 - result(nil)  
326 return 324 return
327 } 325 }
328 326
  327 + if (device.torchMode != torch) {
  328 + device.lockForConfiguration()
  329 + device.torchMode = torch
  330 + device.unlockForConfiguration()
  331 + }
  332 + }
  333 +
  334 + func toggleTorch(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
329 let requestedTorchMode: AVCaptureDevice.TorchMode = call.arguments as! Int == 1 ? .on : .off 335 let requestedTorchMode: AVCaptureDevice.TorchMode = call.arguments as! Int == 1 ? .on : .off
330 336
331 do { 337 do {
332 - if (device.torchMode != requestedTorchMode) {  
333 - try device.lockForConfiguration()  
334 - device.torchMode = requestedTorchMode  
335 - device.unlockForConfiguration()  
336 - }  
337 - 338 + try toggleTorchInternal(requestedTorchMode)
338 result(nil) 339 result(nil)
339 } catch { 340 } catch {
340 result(FlutterError(code: error.localizedDescription, message: nil, details: nil)) 341 result(FlutterError(code: error.localizedDescription, message: nil, details: nil))