krz/domain-dig
an ios app for DNS & SSL analysis
clone: git clone https://gitbay.org/krz/domain-dig.git
v4.6.0: DomainDigShareExtension/ShareViewController.swift · raw
1import UIKit
2import UniformTypeIdentifiers
3
4/// Receives a web URL from the share sheet, extracts its host, and hands it to
5/// the app through the App Group inbox. Shows a brief confirmation and closes;
6/// the app picks up the domain the next time it becomes active.
7final class ShareViewController: UIViewController {
8 private let label = UILabel()
9
10 override func viewDidLoad() {
11 super.viewDidLoad()
12 view.backgroundColor = .systemBackground
13
14 label.text = "Saving…"
15 label.font = .preferredFont(forTextStyle: .headline)
16 label.textAlignment = .center
17 label.numberOfLines = 0
18 label.translatesAutoresizingMaskIntoConstraints = false
19 view.addSubview(label)
20 NSLayoutConstraint.activate([
21 label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
22 label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
23 label.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 24),
24 label.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -24)
25 ])
26
27 extractSharedDomain { [weak self] domain in
28 DispatchQueue.main.async {
29 self?.finish(domain: domain)
30 }
31 }
32 }
33
34 private func extractSharedDomain(completion: @escaping (String?) -> Void) {
35 let providers = (extensionContext?.inputItems ?? [])
36 .compactMap { $0 as? NSExtensionItem }
37 .flatMap { $0.attachments ?? [] }
38
39 guard let provider = providers.first(where: {
40 $0.hasItemConformingToTypeIdentifier(UTType.url.identifier)
41 }) else {
42 completion(nil)
43 return
44 }
45
46 provider.loadItem(forTypeIdentifier: UTType.url.identifier) { item, _ in
47 let url = item as? URL ?? (item as? Data).flatMap { URL(dataRepresentation: $0, relativeTo: nil) }
48 let host = url?.host?.trimmingCharacters(in: .whitespacesAndNewlines)
49 completion(host?.isEmpty == false ? host : nil)
50 }
51 }
52
53 private func finish(domain: String?) {
54 if let domain {
55 DomainDigShareInbox.write(domain: domain)
56 label.text = "Saved \(domain) — open DomainDig to inspect it."
57 } else {
58 label.text = "No web address found."
59 }
60
61 DispatchQueue.main.asyncAfter(deadline: .now() + 1.4) { [weak self] in
62 self?.extensionContext?.completeRequest(returningItems: nil)
63 }
64 }
65}