Why won't RPScreenRecorder stopRecordingWithHandler work? Why won't RPScreenRecorder stopRecordingWithHandler work? xcode xcode

Why won't RPScreenRecorder stopRecordingWithHandler work?


I suspect that if you were to set a breakpoint anywhere inside your guard statement (within stopRecordingCompletionHandler), it would not crash your program or enter the debugger because the else clause of your guard statement is never being called.

In fact, this is expected behavior. We would not expect the else clause to execute unless either controller is equal to nil and therefore cannot be bound to the constant previewController or error exists and therefore does not equal nil.

With guard, the only way the else clause will be called is if the specified conditions are NOT true. Your print statement in the startRecordingWithMicrophoneEnabled closure is being called because it is sitting outside of the guard statement.

So you just need to move some of that logic out of the else clause. You do still want to handle errors there though.

recorder.stopRecordingWithHandler{controller, err in           guard let previewController = controller where err == nil else {          print("2. Failed to stop recording with error \(err!)") // This prints if there was an error          return      }}self.recordBtn.enabled = trueself.stopRecordBtn.enabled = falsepreviewController.previewControllerDelegate = selfself.presentViewController(previewController, animated: true,  completion: nil)print("stopped recording!")

Guard

So just to be sure we're clear on the guard syntax, it's:

guard <condition> else {    <statements to execute if <condition> is not true>}

In your example, you're combining guard with optional binding and a where clause, to create the following situation:

  • If controller is not nil, it will be bound to a constant called previewController.
  • If it is nil then we stop evaluating , never create the constant previewController, and escape to the else clause, which must transfer control with a keyword such as return.
  • If controller is not nil and our constant has been created then we will go ahead and check our where clause.
  • If where evaluates to true (so if there is no error), we will pass the test and be done with the guard statement. else will never be executed.
  • If where evaluates to false, we will execute the else block and anything after the guard statement will not be called.