Share receiver for URLs - save, tag and route elsewhere!
1import UIKit
2import Social
3import UniformTypeIdentifiers
4
5class ShareViewController: UIViewController {
6
7 override func viewDidLoad() {
8 super.viewDidLoad()
9 handleSharedContent()
10 }
11
12 private func handleSharedContent() {
13 guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem,
14 let itemProviders = extensionItem.attachments else {
15 closeExtension()
16 return
17 }
18
19 // Look for URLs
20 for provider in itemProviders {
21 if provider.canLoadObject(ofClass: URL.self) {
22 // Use loadObject with explicit class type
23 provider.loadObject(ofClass: URL.self) { [weak self] (url, error) in
24 if let error = error {
25 print("Error loading URL: \(error)")
26 DispatchQueue.main.async {
27 self?.closeExtension()
28 }
29 return
30 }
31
32 if let url = url {
33 print("Successfully loaded URL: \(url.absoluteString)")
34 self?.sendURLToMainApp(url: url.absoluteString)
35 } else {
36 print("URL was nil after loading")
37 }
38
39 DispatchQueue.main.async {
40 self?.closeExtension()
41 }
42 }
43 return
44 }
45 }
46
47 closeExtension()
48 }
49
50 private func sendURLToMainApp(url: String) {
51 print("Sharing URL to main app: \(url)")
52
53 // Use App Groups to share data
54 if let sharedDefaults = UserDefaults(suiteName: "group.com.dietrich.peek") {
55 sharedDefaults.set(url, forKey: "shared_url")
56 sharedDefaults.set(Date().timeIntervalSince1970, forKey: "shared_url_timestamp")
57 sharedDefaults.synchronize()
58 print("URL saved to App Groups: \(url)")
59 } else {
60 print("Failed to access App Groups - make sure group.com.dietrich.peek is configured")
61 }
62 }
63
64 private func closeExtension() {
65 extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
66 }
67}