|
| 1 | +import Social |
| 2 | +import UIKit |
| 3 | +import UniformTypeIdentifiers |
| 4 | + |
| 5 | +@objc(ShareViewController) |
| 6 | +final class ShareViewController: SLComposeServiceViewController { |
| 7 | + private static let appGroupId = "group.com.softartdev.notedelight" |
| 8 | + private static let sharedTextKey = "shared_text" |
| 9 | + |
| 10 | + override func presentationAnimationDidFinish() { |
| 11 | + super.presentationAnimationDidFinish() |
| 12 | + guard contentText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } |
| 13 | + loadTextFileIfNeeded() |
| 14 | + } |
| 15 | + |
| 16 | + override func isContentValid() -> Bool { |
| 17 | + !contentText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| 18 | + } |
| 19 | + |
| 20 | + override func didSelectPost() { |
| 21 | + let trimmed = contentText.trimmingCharacters(in: .whitespacesAndNewlines) |
| 22 | + if !trimmed.isEmpty { |
| 23 | + UserDefaults(suiteName: Self.appGroupId)?.set(trimmed, forKey: Self.sharedTextKey) |
| 24 | + } |
| 25 | + extensionContext?.completeRequest(returningItems: [], completionHandler: nil) |
| 26 | + } |
| 27 | + |
| 28 | + override func configurationItems() -> [Any]! { |
| 29 | + [] |
| 30 | + } |
| 31 | + |
| 32 | + private func loadTextFileIfNeeded() { |
| 33 | + guard let items = extensionContext?.inputItems as? [NSExtensionItem] else { return } |
| 34 | + for item in items { |
| 35 | + for provider in item.attachments ?? [] where provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) { |
| 36 | + provider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { [weak self] data, _ in |
| 37 | + guard let url = data as? URL, url.isFileURL else { return } |
| 38 | + let accessed = url.startAccessingSecurityScopedResource() |
| 39 | + defer { |
| 40 | + if accessed { |
| 41 | + url.stopAccessingSecurityScopedResource() |
| 42 | + } |
| 43 | + } |
| 44 | + guard let text = try? String(contentsOf: url, encoding: .utf8) else { return } |
| 45 | + DispatchQueue.main.async { |
| 46 | + self?.textView.text = text |
| 47 | + self?.validateContent() |
| 48 | + } |
| 49 | + } |
| 50 | + return |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments