Actualización sin cambiar de app: Share Extension "Quick Update" + clipboard auto-advance
El dolor: para actualizar cada source hay que saltar a la app del banco, copiar/ memorizar el valor y volver. iOS no permite ventanas flotantes editables (PiP es solo vídeo), así que se resuelve con las dos vías sancionadas: Share Extension (target nuevo PortfolioJournalQuickUpdate): - Al compartir texto desde CUALQUIER app aparece "Portfolio Journal": mini-form sobre la app anfitriona con el importe pre-parseado del texto compartido y la siguiente source pendiente del mes preseleccionada. Guardar → sigues en el banco. - Sin Core Data en la extensión: la app publica un espejo de sources activas en el App Group (SharedQuickUpdateSync.refreshMirror) y la extensión encola PendingQuickUpdate; la app los convierte en Snapshots reales al activarse (ingestPending). ExtSharedBridge duplica el contrato (keep-in-sync comentado). - Parser de importes tolerante a locales (12.345,67 € / $1,234.56 / 1234,5). - UI localizada en los 7 idiomas (lproj propios de la extensión). - pbxproj: target app-extension completo (sync group, embed, dependency, configs) replicando el patrón del widget. Entitlements solo con App Group. Clipboard auto-advance en Quick Update: - Al volver a la app con un importe copiado: banner de un tap "Pegar X en <source>" que rellena la siguiente source vacía y avanza el foco a la siguiente. - Badge NEXT en la fila activa; no repite sugerencias del mismo clipboard. Script de upload: -allowProvisioningUpdates + API key también en el archive para que el bundle id nuevo de la extensión se registre automáticamente. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015qUZrBusG82T37R7PeokqJ
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
import Foundation
|
||||
|
||||
// MARK: - App Group bridge (extension side)
|
||||
//
|
||||
// KEEP IN SYNC with PortfolioJournal/Utilities/SharedQuickUpdate.swift — same
|
||||
// UserDefaults suite, same keys, same JSON shapes. Duplicated here so the
|
||||
// extension stays self-contained (no Core Data, no app-target sources).
|
||||
|
||||
struct ExtSourceInfo: Codable, Identifiable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let latestValue: Double
|
||||
let currencyCode: String
|
||||
var updatedThisMonth: Bool
|
||||
}
|
||||
|
||||
struct ExtPendingUpdate: Codable {
|
||||
let sourceId: UUID
|
||||
let amount: Double
|
||||
let capturedAt: Date
|
||||
}
|
||||
|
||||
enum ExtSharedStore {
|
||||
static let appGroupIdentifier = "group.com.alexandrevazquez.portfoliojournal"
|
||||
private static let mirrorKey = "sharedSourceMirror"
|
||||
private static let queueKey = "pendingQuickUpdates"
|
||||
|
||||
private static var defaults: UserDefaults? {
|
||||
UserDefaults(suiteName: appGroupIdentifier)
|
||||
}
|
||||
|
||||
static func readMirror() -> [ExtSourceInfo] {
|
||||
guard let data = defaults?.data(forKey: mirrorKey),
|
||||
let decoded = try? JSONDecoder().decode([ExtSourceInfo].self, from: data) else { return [] }
|
||||
return decoded
|
||||
}
|
||||
|
||||
static func appendPending(_ update: ExtPendingUpdate) {
|
||||
var queue: [ExtPendingUpdate] = []
|
||||
if let data = defaults?.data(forKey: queueKey),
|
||||
let decoded = try? JSONDecoder().decode([ExtPendingUpdate].self, from: data) {
|
||||
queue = decoded
|
||||
}
|
||||
queue.append(update)
|
||||
if let data = try? JSONEncoder().encode(queue) {
|
||||
defaults?.set(data, forKey: queueKey)
|
||||
}
|
||||
// Mark the source as updated so the next share preselects the following one.
|
||||
var mirror = readMirror()
|
||||
if let idx = mirror.firstIndex(where: { $0.id == update.sourceId }) {
|
||||
mirror[idx].updatedThisMonth = true
|
||||
if let data = try? JSONEncoder().encode(mirror) {
|
||||
defaults?.set(data, forKey: mirrorKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Amount parsing (locale-tolerant)
|
||||
|
||||
enum ExtAmountParser {
|
||||
/// Parses strings like "12.345,67 €", "$1,234.56", "1234,5" into a Decimal.
|
||||
static func parse(_ raw: String) -> Decimal? {
|
||||
// Strip everything except digits and separators.
|
||||
let cleaned = raw.filter { $0.isNumber || $0 == "." || $0 == "," }
|
||||
guard !cleaned.isEmpty else { return nil }
|
||||
|
||||
let lastDot = cleaned.lastIndex(of: ".")
|
||||
let lastComma = cleaned.lastIndex(of: ",")
|
||||
|
||||
var normalized = cleaned
|
||||
switch (lastDot, lastComma) {
|
||||
case let (dot?, comma?):
|
||||
// Both present: the LAST one is the decimal separator.
|
||||
if dot > comma {
|
||||
normalized = cleaned.replacingOccurrences(of: ",", with: "")
|
||||
} else {
|
||||
normalized = cleaned.replacingOccurrences(of: ".", with: "")
|
||||
.replacingOccurrences(of: ",", with: ".")
|
||||
}
|
||||
case (nil, let comma?):
|
||||
// Only commas: decimal if the trailing group isn't exactly 3 digits.
|
||||
let trailing = cleaned.distance(from: cleaned.index(after: comma), to: cleaned.endIndex)
|
||||
if trailing == 3 && cleaned.filter({ $0 == "," }).count > 0 && cleaned.count > 4 {
|
||||
normalized = cleaned.replacingOccurrences(of: ",", with: "")
|
||||
} else {
|
||||
normalized = cleaned.replacingOccurrences(of: ",", with: ".")
|
||||
}
|
||||
case (let dot?, nil):
|
||||
// Only dots: decimal if the trailing group isn't exactly 3 digits.
|
||||
let trailing = cleaned.distance(from: cleaned.index(after: dot), to: cleaned.endIndex)
|
||||
if trailing == 3 && cleaned.filter({ $0 == "." }).count > 1 {
|
||||
normalized = cleaned.replacingOccurrences(of: ".", with: "")
|
||||
}
|
||||
case (nil, nil):
|
||||
break
|
||||
}
|
||||
|
||||
guard let value = Decimal(string: normalized, locale: Locale(identifier: "en_US_POSIX")),
|
||||
value > 0 else { return nil }
|
||||
return value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Portfolio Journal</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>$(MARKETING_VERSION)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
<false/>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>NSExtensionActivationRule</key>
|
||||
<dict>
|
||||
<key>NSExtensionActivationSupportsText</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.share-services</string>
|
||||
<key>NSExtensionPrincipalClass</key>
|
||||
<string>$(PRODUCT_MODULE_NAME).ShareViewController</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,198 @@
|
||||
import UIKit
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
// MARK: - Quick Update share extension
|
||||
//
|
||||
// Appears in the share sheet when the user shares/selects text in ANY app (their
|
||||
// bank, broker…). Shows a compact form floating over the host app: pick a source
|
||||
// (the next one pending this month is preselected), amount prefilled from the
|
||||
// shared text, save — and the user never leaves the bank app. The main app turns
|
||||
// these captures into real snapshots on its next activation.
|
||||
|
||||
@objc(ShareViewController)
|
||||
final class ShareViewController: UIViewController {
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
view.backgroundColor = .clear
|
||||
extractSharedText { [weak self] text in
|
||||
DispatchQueue.main.async {
|
||||
self?.presentForm(sharedText: text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func extractSharedText(completion: @escaping (String?) -> Void) {
|
||||
let providers = (extensionContext?.inputItems as? [NSExtensionItem])?
|
||||
.compactMap { $0.attachments }
|
||||
.flatMap { $0 } ?? []
|
||||
|
||||
guard let provider = providers.first(where: {
|
||||
$0.hasItemConformingToTypeIdentifier(UTType.plainText.identifier)
|
||||
}) else {
|
||||
completion(nil)
|
||||
return
|
||||
}
|
||||
|
||||
provider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { item, _ in
|
||||
completion(item as? String)
|
||||
}
|
||||
}
|
||||
|
||||
private func presentForm(sharedText: String?) {
|
||||
let form = QuickUpdateShareView(
|
||||
sharedText: sharedText,
|
||||
onDone: { [weak self] in
|
||||
self?.extensionContext?.completeRequest(returningItems: nil)
|
||||
},
|
||||
onCancel: { [weak self] in
|
||||
self?.extensionContext?.cancelRequest(withError: NSError(
|
||||
domain: "com.alexandrevazquez.PortfolioJournal.QuickUpdate",
|
||||
code: NSUserCancelledError
|
||||
))
|
||||
}
|
||||
)
|
||||
let host = UIHostingController(rootView: form)
|
||||
host.modalPresentationStyle = .formSheet
|
||||
if let sheet = host.sheetPresentationController {
|
||||
sheet.detents = [.medium(), .large()]
|
||||
sheet.prefersGrabberVisible = true
|
||||
}
|
||||
host.isModalInPresentation = true
|
||||
present(host, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Form
|
||||
|
||||
struct QuickUpdateShareView: View {
|
||||
let sharedText: String?
|
||||
let onDone: () -> Void
|
||||
let onCancel: () -> Void
|
||||
|
||||
@State private var sources: [ExtSourceInfo] = []
|
||||
@State private var selectedSourceId: UUID?
|
||||
@State private var amountText: String = ""
|
||||
@State private var saved = false
|
||||
@FocusState private var amountFocused: Bool
|
||||
|
||||
private var parsedAmount: Decimal? {
|
||||
ExtAmountParser.parse(amountText)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
Group {
|
||||
if sources.isEmpty {
|
||||
ContentUnavailableView(
|
||||
String(localized: "ext_no_sources_title"),
|
||||
systemImage: "list.bullet",
|
||||
description: Text(String(localized: "ext_no_sources_body"))
|
||||
)
|
||||
} else if saved {
|
||||
savedConfirmation
|
||||
} else {
|
||||
form
|
||||
}
|
||||
}
|
||||
.navigationTitle(String(localized: "ext_title"))
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .cancellationAction) {
|
||||
Button(String(localized: "ext_cancel")) { onCancel() }
|
||||
}
|
||||
if !sources.isEmpty && !saved {
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button(String(localized: "ext_save")) { save() }
|
||||
.disabled(parsedAmount == nil || selectedSourceId == nil)
|
||||
.fontWeight(.semibold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.onAppear(perform: load)
|
||||
}
|
||||
|
||||
private var form: some View {
|
||||
Form {
|
||||
Section(String(localized: "ext_amount_section")) {
|
||||
TextField(String(localized: "ext_amount_placeholder"), text: $amountText)
|
||||
.keyboardType(.decimalPad)
|
||||
.font(.title3.weight(.semibold))
|
||||
.focused($amountFocused)
|
||||
}
|
||||
|
||||
Section(String(localized: "ext_source_section")) {
|
||||
ForEach(sources) { source in
|
||||
Button {
|
||||
selectedSourceId = source.id
|
||||
} label: {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(source.name)
|
||||
.foregroundColor(.primary)
|
||||
.font(.subheadline.weight(.medium))
|
||||
if source.updatedThisMonth {
|
||||
Text(String(localized: "ext_already_updated"))
|
||||
.font(.caption2)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
if selectedSourceId == source.id {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.foregroundColor(.blue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var savedConfirmation: some View {
|
||||
VStack(spacing: 14) {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.font(.system(size: 52))
|
||||
.foregroundColor(.green)
|
||||
Text(String(localized: "ext_saved_title"))
|
||||
.font(.headline)
|
||||
Text(String(localized: "ext_saved_body"))
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding(32)
|
||||
.onAppear {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { onDone() }
|
||||
}
|
||||
}
|
||||
|
||||
private func load() {
|
||||
var mirror = ExtSharedStore.readMirror()
|
||||
// Pending-first ordering: the sources still waiting this month come on top.
|
||||
mirror.sort { a, b in
|
||||
if a.updatedThisMonth != b.updatedThisMonth { return !a.updatedThisMonth }
|
||||
return a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending
|
||||
}
|
||||
sources = mirror
|
||||
selectedSourceId = mirror.first(where: { !$0.updatedThisMonth })?.id ?? mirror.first?.id
|
||||
|
||||
if let sharedText, let parsed = ExtAmountParser.parse(sharedText) {
|
||||
amountText = "\(parsed)"
|
||||
} else {
|
||||
amountFocused = true
|
||||
}
|
||||
}
|
||||
|
||||
private func save() {
|
||||
guard let amount = parsedAmount, let sourceId = selectedSourceId else { return }
|
||||
ExtSharedStore.appendPending(ExtPendingUpdate(
|
||||
sourceId: sourceId,
|
||||
amount: NSDecimalNumber(decimal: amount).doubleValue,
|
||||
capturedAt: Date()
|
||||
))
|
||||
withAnimation { saved = true }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "Schnell-Update";
|
||||
"ext_cancel" = "Abbrechen";
|
||||
"ext_save" = "Sichern";
|
||||
"ext_amount_section" = "Betrag";
|
||||
"ext_amount_placeholder" = "0,00";
|
||||
"ext_source_section" = "Quelle";
|
||||
"ext_already_updated" = "Diesen Monat aktualisiert";
|
||||
"ext_saved_title" = "Gesichert!";
|
||||
"ext_saved_body" = "Erscheint in Portfolio Journal beim nächsten Öffnen.";
|
||||
"ext_no_sources_title" = "Noch keine Quellen";
|
||||
"ext_no_sources_body" = "Öffne Portfolio Journal einmal, damit deine Quellen hier erscheinen.";
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "Quick Update";
|
||||
"ext_cancel" = "Cancel";
|
||||
"ext_save" = "Save";
|
||||
"ext_amount_section" = "Amount";
|
||||
"ext_amount_placeholder" = "0.00";
|
||||
"ext_source_section" = "Source";
|
||||
"ext_already_updated" = "Updated this month";
|
||||
"ext_saved_title" = "Saved!";
|
||||
"ext_saved_body" = "It will appear in Portfolio Journal the next time you open it.";
|
||||
"ext_no_sources_title" = "No sources yet";
|
||||
"ext_no_sources_body" = "Open Portfolio Journal once so your sources appear here.";
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "Actualización rápida";
|
||||
"ext_cancel" = "Cancelar";
|
||||
"ext_save" = "Guardar";
|
||||
"ext_amount_section" = "Importe";
|
||||
"ext_amount_placeholder" = "0,00";
|
||||
"ext_source_section" = "Fuente";
|
||||
"ext_already_updated" = "Actualizada este mes";
|
||||
"ext_saved_title" = "¡Guardado!";
|
||||
"ext_saved_body" = "Aparecerá en Portfolio Journal la próxima vez que la abras.";
|
||||
"ext_no_sources_title" = "Aún no hay fuentes";
|
||||
"ext_no_sources_body" = "Abre Portfolio Journal una vez para que tus fuentes aparezcan aquí.";
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "Mise à jour rapide";
|
||||
"ext_cancel" = "Annuler";
|
||||
"ext_save" = "Enregistrer";
|
||||
"ext_amount_section" = "Montant";
|
||||
"ext_amount_placeholder" = "0,00";
|
||||
"ext_source_section" = "Source";
|
||||
"ext_already_updated" = "Déjà à jour ce mois-ci";
|
||||
"ext_saved_title" = "Enregistré !";
|
||||
"ext_saved_body" = "Apparaîtra dans Portfolio Journal à la prochaine ouverture.";
|
||||
"ext_no_sources_title" = "Aucune source";
|
||||
"ext_no_sources_body" = "Ouvrez Portfolio Journal une fois pour que vos sources apparaissent ici.";
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "Aggiornamento rapido";
|
||||
"ext_cancel" = "Annulla";
|
||||
"ext_save" = "Salva";
|
||||
"ext_amount_section" = "Importo";
|
||||
"ext_amount_placeholder" = "0,00";
|
||||
"ext_source_section" = "Fonte";
|
||||
"ext_already_updated" = "Aggiornata questo mese";
|
||||
"ext_saved_title" = "Salvato!";
|
||||
"ext_saved_body" = "Apparirà in Portfolio Journal alla prossima apertura.";
|
||||
"ext_no_sources_title" = "Nessuna fonte";
|
||||
"ext_no_sources_body" = "Apri Portfolio Journal una volta perché le tue fonti appaiano qui.";
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "クイック更新";
|
||||
"ext_cancel" = "キャンセル";
|
||||
"ext_save" = "保存";
|
||||
"ext_amount_section" = "金額";
|
||||
"ext_amount_placeholder" = "0";
|
||||
"ext_source_section" = "投資先";
|
||||
"ext_already_updated" = "今月更新済み";
|
||||
"ext_saved_title" = "保存しました";
|
||||
"ext_saved_body" = "次回Portfolio Journalを開いたときに反映されます。";
|
||||
"ext_no_sources_title" = "投資先がありません";
|
||||
"ext_no_sources_body" = "一度Portfolio Journalを開くと、ここに投資先が表示されます。";
|
||||
@@ -0,0 +1,11 @@
|
||||
"ext_title" = "Atualização rápida";
|
||||
"ext_cancel" = "Cancelar";
|
||||
"ext_save" = "Salvar";
|
||||
"ext_amount_section" = "Valor";
|
||||
"ext_amount_placeholder" = "0,00";
|
||||
"ext_source_section" = "Fonte";
|
||||
"ext_already_updated" = "Atualizada este mês";
|
||||
"ext_saved_title" = "Salvo!";
|
||||
"ext_saved_body" = "Aparecerá no Portfolio Journal na próxima vez que você abrir.";
|
||||
"ext_no_sources_title" = "Nenhuma fonte";
|
||||
"ext_no_sources_body" = "Abra o Portfolio Journal uma vez para que suas fontes apareçam aqui.";
|
||||
Reference in New Issue
Block a user