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 notnil
, it will be bound to a constant calledpreviewController
. - If it is
nil
then we stop evaluating , never create the constantpreviewController
, and escape to theelse
clause, which must transfer control with a keyword such asreturn
. - If
controller
is notnil
and our constant has been created then we will go ahead and check ourwhere
clause. - If
where
evaluates totrue
(so if there is no error), we will pass the test and be done with theguard
statement.else
will never be executed. - If
where
evaluates tofalse
, we will execute theelse
block and anything after theguard
statement will not be called.