[iOS] NSDataDetector에서 발생한 이슈 공유 iOS

구글신을 통해 찾은 string에서 link 찾아내기. 

당연하게도(?) 간단히 복붙해서 사용중이었다. 


extension String {

    public func extractAllLinks() -> [NSTextCheckingResult]? {
        let types: NSTextCheckingResult.CheckingType = .link

        let detector = tryNSDataDetector(types: types.rawValue)
        guard let detect = detector else { return nil }

        let matches = detect.matches(inselfoptions: [], rangeNSRange(location0lengthself.count))
        return matches
    }

}


하지만, 당연하게도(?) 버그가 발생했으니...


링크가 텍스트의 하단에 존재할 경우, http://gsstudio.egloos.com/category/iOS 이런 링크일 경우


matches 에는 http://gsstudio.egloos.com/categ 중간에 잘라서 찾아내는게 아닌가.



빠르게 결론만 얘기하자면 range가 잘못된 문제였던듯 싶다. 



let matches = detect.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count))



range의 length를 utf16으로 값을 정확히 잡아주었다. 한글 등등 때문에 정확히 range를 못잡아서 짤린 것 같다. 


텍스트는 항상 유니코드 조심하자... 


끝.




덧글

댓글 입력 영역


adsence 160x600