Files

16 lines
764 B
Swift

import Foundation
/// A web or mail address in the plain text of the page.
public enum PageLink {
/// The address that covers the character at `index`, and its range; nil when no address is there.
public static func link(in text: NSString, at index: Int) -> (url: URL, range: NSRange)? {
guard index >= 0, index < text.length,
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return nil }
let line = text.lineRange(for: NSRange(location: index, length: 0))
for match in detector.matches(in: text as String, range: line) where NSLocationInRange(index, match.range) {
if let url = match.url { return (url, match.range) }
}
return nil
}
}