Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Fix #661: Open in Brave now opens the first URL found in shared content
Browse files Browse the repository at this point in the history
  • Loading branch information
kylehickinson committed Jul 22, 2019
1 parent 9811303 commit db843c1
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions BraveShareTo/ShareToBraveViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ class ShareToBraveViewController: SLComposeServiceViewController {
return URL(string: "brave://open-url?url=\(url)")
}

private func firstURL(in string: String) -> URL? {
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
if let match = detector.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)),
let range = Range(match.range, in: string) {
return URL(string: String(string[range]))
}
} catch {
return nil
}
return nil
}

override func configurationItems() -> [Any]! {
guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem] else {
return []
Expand All @@ -33,19 +46,22 @@ class ShareToBraveViewController: SLComposeServiceViewController {
}

provider.loadItem(of: provider.isUrl ? kUTTypeURL : kUTTypeText) { item, error in
var urlItem: URL!
var urlItem: URL?

// We can get urls from other apps as a kUTTypeText type, for example from Apple's mail.app.
if let text = item as? String {
urlItem = URL(string: text)
urlItem = self.firstURL(in: text)
} else if let url = item as? URL {
urlItem = url
urlItem = self.firstURL(in: url.absoluteString)
} else {
self.cancel()
return
}

if let braveUrl = urlItem.absoluteString.addingPercentEncoding(withAllowedCharacters: .alphanumerics).flatMap(self.urlScheme) {
// Just open the app if we don't find a url. In the future we could
// use this entry point to search instead of open a given URL
let urlString = urlItem?.absoluteString ?? ""
if let braveUrl = urlString.addingPercentEncoding(withAllowedCharacters: .alphanumerics).flatMap(self.urlScheme) {
self.handleUrl(braveUrl)
}
}
Expand Down

0 comments on commit db843c1

Please sign in to comment.