1

enter image description here

Basically Im using the vision framework to find keywords the user searches for in the UITextField but if there is more than one of the same words on a given line it only detects the first word. For example lets say I have an image and the text has "in in in in in in" only the first "in" will get detected and the rest won't. Only way it will detect the other words if they are on separate lines like on the right side of the image. Why does this happen?

Here is a pic explaining the problem and my code:

 func detectTextHandler(request: VNRequest, error: Error?) {

    guard let results = request.results as? [VNRecognizedTextObservation] else {
        return
    }

    DispatchQueue.main.async {

    self.previewView.layer.sublayers?.removeSubrange(1...)
        for visionResult in results {
            guard let candidate = visionResult.topCandidates(1).first else {
            continue
        }


            let words = candidate.string.split{ $0.isWhitespace }.map{ String($0)}



               for word in words {
                if let wordRange = candidate.string.range(of: word, options: .caseInsensitive),


               let boxObservation = try? candidate.boundingBox(for: wordRange) {

                    if self.searchTextField.text == word
                        {
                print(word)
                self.highlightLetters(box: boxObservation)//highlights words
          }
        }
      }
    }
  }
}
xcode22
  • 118
  • 1
  • 9
  • can you check visionResult.topCandidates(1) are have more than one object or not? because the code only use first object, you can try to change it to last too – aiwiguna Mar 11 '20 at 01:31
  • I tried putting 2 instead of 1 but same result. Could it be the range(of:) part because I was looking at the definition and it says `Finds and returns the range of the first occurrence of a given string within a given range of the String, subject to given options, using the specified locale, if any.` It only finds the first occuruence of a given string so Im thinking it might be that part thats giving me trouble. What do you think? – xcode22 Mar 11 '20 at 12:55
  • 1
    Does this answer your question? [Swift find all occurrences of a substring](https://stackoverflow.com/questions/40413218/swift-find-all-occurrences-of-a-substring) – MwcsMac Mar 11 '20 at 13:15
  • No I get an error `NSRangeException', reason: '*** -[__NSCFString rangeOfString:options:range:locale:]: Range {0, 9} out of bounds; string length 7'` – xcode22 Mar 11 '20 at 13:28
  • @MwcsMac Yes that worked now. I had to change some of the code but it worked if you answer the question I can give you the check mark. – xcode22 Mar 11 '20 at 17:49

0 Answers0