Search code examples
iosswiftavcapturesessionapple-vision

Checking if a bool is true for x seconds - Swift


I am using VNDetectRectanglesRequest and I want to check if the CGRect of my detected rectangle is within another CGRect for 1 second. Here is my code so far:

let x = self.view.frame.width * detectedRectangle.boundingBox.origin.x
let height = self.view.frame.height * detectedRectangle.boundingBox.height
let y = self.view.frame.height * (1 - detectedRectangle.boundingBox.origin.y) - height
let width = self.view.frame.width * detectedRectangle.boundingBox.width
let rectangleDetected = CGRect(x: x, y: y, width: width, height: height)

self.redView.frame = rectangleDetected

let outsideGuideRect = CGRect(x: self.boardMargin*1/2, y: (self.view.frame.height-self.view.frame.width+1/2*self.boardMargin)/2, width: self.view.frame.width-1/2*self.boardMargin, height: self.view.frame.width-1/2*self.boardMargin)
print(outsideGuideRect.contains(rectangleDetected))
if outsideGuideRect.contains(sudokuBoardRect) {

    // HERE I WANT TO CHECK IF THIS IF STATEMENT IS TRUE FOR 1 second

}

The above code is in a function that is run every frame. How could I check if the if statement is true for one second? Thank you!


Solution

  • What I understood form your question is, "you want to perform an action after 1 sec once your rect B come inside rect A (without leaving)".

    Following can be a probable solution that I got from top of my head, there can be something better to this, if we think little more.

    //initialize _insideRect as false globally
    if outsideGuideRect.contains(sudokuBoardRect) {
        // HERE I WANT TO CHECK IF THIS IF STATEMENT IS TRUE FOR 1 second
        if (!_insideRect) {
          _insideRect = true;
          DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
            if (_insideRect) {
              // your function here
            }
          }
        }
    }else{
        _insideRect = false;
    }