Last active
February 6, 2024 09:53
-
-
Save nearfri/b06249a18ea02b7fecdc7536f9889d28 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension URL { | |
// https://apple.com -> https://apple.com | |
// https://애플.com -> https://xn--9e5bq00a.com | |
// https://apple.wow -> https://apple.wow | |
// apple.com -> http://apple.com | |
// 애플.com -> http://xn--9e5bq00a.com | |
// apple.wow -> nil | |
// apple -> nil | |
init?(link: String) { | |
let checkingType = NSTextCheckingResult.CheckingType.link | |
guard let detector = try? NSDataDetector(types: checkingType.rawValue) else { | |
preconditionFailure() | |
} | |
let range = NSRange(location: 0, length: link.utf16.count) | |
guard let match = detector.firstMatch(in: link, options: [.anchored], range: range), | |
let url = match.url, match.range == range | |
else { return nil } | |
self = url | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment