From 4e9317d45c8c32e3d398531533e9064c6734f8ad Mon Sep 17 00:00:00 2001 From: Giuseppe Travasoni Date: Fri, 17 Mar 2023 16:54:05 +0100 Subject: [PATCH] fix: possible crash if not possible to instatiate URL from string --- .../Text/PDFAttributedTextObject.swift | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Source/Internal/Text/PDFAttributedTextObject.swift b/Source/Internal/Text/PDFAttributedTextObject.swift index 6069b88a..818a3ed2 100644 --- a/Source/Internal/Text/PDFAttributedTextObject.swift +++ b/Source/Internal/Text/PDFAttributedTextObject.swift @@ -199,24 +199,25 @@ internal class PDFAttributedTextObject: PDFRenderObject { } for link in links { for metric in lineMetrics { - if let intersection = NSRange(location: metric.range.location, - length: metric.range.length).intersection(link.range) { - let startOffset = CTLineGetOffsetForStringIndex(metric.line, intersection.location, nil) - let endOffset = CTLineGetOffsetForStringIndex(metric.line, intersection.location + intersection.length, nil) - - let linkFrame = CGRect( - x: self.frame.origin.x + startOffset, - y: metric.bounds.origin.y, - width: endOffset - startOffset, - height: metric.bounds.height) - attributes.append((attribute: .link(url: URL(string: link.url)!), frame: linkFrame)) - - if debug { - PDFGraphics.drawRect(in: context, - rect: linkFrame, - outline: .none, - fill: Color.red.withAlphaComponent(0.4)) - } + guard let intersection = NSRange(location: metric.range.location, length: metric.range.length).intersection(link.range), + let url = URL(string: link.url) else { + break + } + let startOffset = CTLineGetOffsetForStringIndex(metric.line, intersection.location, nil) + let endOffset = CTLineGetOffsetForStringIndex(metric.line, intersection.location + intersection.length, nil) + + let linkFrame = CGRect( + x: self.frame.origin.x + startOffset, + y: metric.bounds.origin.y, + width: endOffset - startOffset, + height: metric.bounds.height) + attributes.append((attribute: .link(url: url), frame: linkFrame)) + + if debug { + PDFGraphics.drawRect(in: context, + rect: linkFrame, + outline: .none, + fill: Color.red.withAlphaComponent(0.4)) } } }