Skip to content

Commit

Permalink
Merge pull request #56 from vinnyt/UseDataDetector
Browse files Browse the repository at this point in the history
use data detector to extract URLs from text so that plain urls will b…
  • Loading branch information
LeonardoCardoso authored Jul 6, 2017
2 parents c679757 + 81df858 commit c6153c7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
12 changes: 8 additions & 4 deletions Sources/SwiftLinkPreview.swift
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,15 @@ extension SwiftLinkPreview {

// Extract first URL from text
open func extractURL(text: String) -> URL? {
let pieces: [String] = text.components(separatedBy: .whitespacesAndNewlines).filter { $0.trim.isValidURL() }
if pieces.count > 0, let url = URL(string: pieces[0]) {
return url
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let range = NSRange(location: 0, length: text.characters.count)
let matches = detector.matches(in: text, options: [], range: range)

return matches.flatMap { $0.url }.first
} catch {
return nil
}
return nil
}

// Unshorten URL by following redirections
Expand Down
12 changes: 6 additions & 6 deletions SwiftLinkPreviewTests/URLs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct URLs {
static let bunch = [
[
"aaa www.google.com aaa",
"www.google.com",
"http://www.google.com",
"www.google.com"
],
[
Expand All @@ -36,12 +36,12 @@ struct URLs {
],
[
"ddd ios.leocardz.com/swift-link-preview/ ddd",
"ios.leocardz.com/swift-link-preview/",
"http://ios.leocardz.com/swift-link-preview/",
"ios.leocardz.com"
],
[
"ddd ios.leocardz.com ddd",
"ios.leocardz.com",
"http://ios.leocardz.com",
"ios.leocardz.com"
],
[
Expand All @@ -51,7 +51,7 @@ struct URLs {
],
[
"fff theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy fff",
"theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy",
"http://theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy",
"theverge.com"
],
[
Expand All @@ -71,7 +71,7 @@ struct URLs {
],
[
"hhh twitter.com hhh",
"twitter.com",
"http://twitter.com",
"twitter.com"
],
[
Expand Down Expand Up @@ -127,4 +127,4 @@ struct URLs {
]


}
}

0 comments on commit c6153c7

Please sign in to comment.