<?xml version="1.0" encoding="utf-8"?>





<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="es" xml:base="https://www.obocat.com/">
  <title type="text">Daniel Toranzo Pérez — Blog (ES)</title>
  <subtitle type="text">Notas sobre desarrollo iOS, arquitectura, rendimiento y las decisiones que hay detrás de los productos en los que trabajo.</subtitle>
  <link href="https://www.obocat.com/feed-es.xml" rel="self" type="application/atom+xml"/>
  <link href="https://www.obocat.com/blog/" rel="alternate" type="text/html" hreflang="es"/>
  <link href="https://www.obocat.com/feed-en.xml" rel="alternate" type="application/atom+xml" hreflang="en"/>
  <id>https://www.obocat.com/feed-es.xml</id>
  <updated>2026-11-23T08:00:00+00:00</updated>
  <author>
    <name>Daniel Toranzo Pérez</name>
    <uri>https://www.obocat.com/</uri>
  </author>
  <rights>© 2026 Daniel Toranzo Pérez</rights>
  <logo>https://www.obocat.com/images/og-card.png?v=2</logo>
  <icon>https://www.obocat.com/favicon.png</icon>
  <generator uri="https://jekyllrb.com/">Jekyll</generator>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">autoreleasepool en Swift: cuando ARC no es suficiente</title>
    <link href="https://www.obocat.com/blog/2026/11/23/autoreleasepool-swift/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/11/23/autoreleasepool-swift/</id>
    <published>2026-11-23T08:00:00+00:00</published>
    <updated>2026-11-23T08:00:00+00:00</updated>
    <summary type="text">Por qué un bucle con APIs de Objective-C puede disparar la memoria aunque uses ARC, y cómo usar autoreleasepool para acotar el pico.</summary>
    
    <category term="iOS"/>
    
    <category term="Swift"/>
    
    <category term="Memory"/>
    
    <category term="ARC"/>
    
    <category term="Performance"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/11/23/autoreleasepool-swift/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;Imagina que tienes una carpeta con miles de fotos. Tu código recorre los archivos, carga cada imagen, la comprime de nuevo y guarda el resultado. Cada iteración es independiente, así que esperarías que el consumo de memoria se mantuviera más o menos estable.&lt;/p&gt;

  &lt;p&gt;Pero ocurre justo lo contrario: la memoria no deja de crecer hasta que iOS termina cerrando la app.&lt;/p&gt;

  &lt;p&gt;No hay ningún retain cycle evidente (un ciclo de referencias fuertes) ni un array acumulando todas las imágenes. El problema está un poco más abajo: en el autorelease pool de Objective-C.&lt;/p&gt;

  &lt;p&gt;Este es el patrón que suele aparecer:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIKit&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reencodeImagesWithoutPool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;urls&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;directory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;urls&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIImage&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;contentsOfFile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
              &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;jpegData&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;compressionQuality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;filename&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;deletingPathExtension&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lastPathComponent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;.jpg&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;write&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;directory&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;appendingPathComponent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;filename&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;A primera vista, el código parece correcto. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;image&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;data&lt;/code&gt; son referencias locales; cuando termina la iteración, no deberían quedar vivas. Pero ARC no es el único sistema de memoria que está trabajando aquí.&lt;/p&gt;

  &lt;h2 id=&quot;lo-que-arc-s-garantiza&quot;&gt;Lo que ARC sí garantiza&lt;/h2&gt;

  &lt;p&gt;En Swift, un objeto empieza a vivir en su inicialización y su vida garantizada termina en su último uso. El compilador inserta operaciones &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;retain&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;release&lt;/code&gt;; según las optimizaciones, el objeto puede liberarse justo después de ese último uso o más tarde. Lo que garantiza es que el objeto seguirá vivo hasta ese momento, no que se libere exactamente entonces. Es distinto de C++, donde el cierre del bloque marca el final de la vida del objeto.&lt;/p&gt;

  &lt;p&gt;Apple lo explica en la sesión &lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2021/10216/&quot;&gt;ARC in Swift: Basics and beyond&lt;/a&gt; de la WWDC21. Decir que «Swift libera los objetos justo cuando dejan de hacer falta» es quedarse a medias. ARC suele liberar los objetos cerca de su último uso, pero no es un recolector de basura ni garantiza que se liberen exactamente en ese momento.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Matiz:&lt;/strong&gt; ARC garantiza que un objeto vive al menos hasta su último uso. No garantiza que muera exactamente ahí. Y los objetos que Objective-C envía a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autorelease&lt;/code&gt; no siguen las reglas de ARC de Swift.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Para objetos puramente Swift, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; normalmente no hace nada: no hay ningún &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autorelease&lt;/code&gt; que drenar. El problema aparece cuando el bucle llama a APIs de Foundation o UIKit que, por debajo, siguen siendo Objective-C.&lt;/p&gt;

  &lt;h2 id=&quot;la-parte-de-objective-c-que-sigue-interviniendo&quot;&gt;La parte de Objective-C que sigue interviniendo&lt;/h2&gt;

  &lt;p&gt;Cuando un objeto recibe &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autorelease&lt;/code&gt;, su liberación se pospone. En lugar de liberarse inmediatamente, queda registrado en el pool actual. Cuando el pool se drena, recibe un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;release&lt;/code&gt; por cada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autorelease&lt;/code&gt; que recibió dentro de ese bloque.&lt;/p&gt;

  &lt;p&gt;UIKit y AppKit crean un pool al principio de cada iteración del run loop y lo drenan al final. Por eso, en una acción normal de la interfaz, no tienes que preocuparte: el sistema ya está haciendo el trabajo. El problema aparece cuando el bucle entero se ejecuta dentro de una misma iteración del run loop. Todos esos objetos se acumulan en el pool hasta que termina el lote y se drena.&lt;/p&gt;

  &lt;p&gt;La guía de memoria de Apple lo dice de forma explícita: si escribes un bucle que crea muchos objetos temporales, puedes usar un pool dentro del bucle para reducir el pico de memoria. También recomienda crear uno al empezar un hilo secundario. No es una reliquia de la época manual: Foundation y UIKit siguen siendo Objective-C en gran parte, y algunas APIs modernas puentean a Objective-C según la versión del sistema o los argumentos que reciben.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Ojo:&lt;/strong&gt; no hay una lista fiable de qué APIs usan &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autorelease&lt;/code&gt; por dentro. Hasta una API aparentemente Swift como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Data(contentsOf:)&lt;/code&gt; se ha comportado distinto entre versiones. La regla no es memorizar nombres: es medir y acotar cuando veas el patrón.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;la-solucin-un-pool-por-iteracin&quot;&gt;La solución: un pool por iteración&lt;/h2&gt;

  &lt;p&gt;La versión con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; cambia muy poco:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIKit&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reencodeImages&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;urls&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;directory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;urls&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;autoreleasepool&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIImage&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;contentsOfFile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;jpegData&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;compressionQuality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

            &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;filename&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;deletingPathExtension&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lastPathComponent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;.jpg&quot;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;write&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;directory&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;appendingPathComponent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;filename&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Todo el trabajo de esa iteración queda dentro del pool. Al terminar el bloque, los objetos autoreleased de esa iteración reciben su &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;release&lt;/code&gt;. Si no se puede cargar una imagen o generar sus datos, el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;return&lt;/code&gt; termina únicamente el closure de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt;; el bucle continúa con la siguiente URL. Si el cuerpo lanza un error, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;try&lt;/code&gt; lo propaga; no necesitas un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;do/catch&lt;/code&gt; solo para el pool.&lt;/p&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; no es una palabra clave: es una función del módulo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ObjectiveC&lt;/code&gt; que Foundation y UIKit reexportan.&lt;/p&gt;

  &lt;p&gt;El pool va &lt;strong&gt;dentro&lt;/strong&gt; del bucle, no alrededor. Este pseudocódigo no sirve:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;autoreleasepool&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;urls&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// ...&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Ahí el pool se vacía al final del lote, justo cuando ya no importa. La unidad que quieres acotar es la iteración, no la operación completa.&lt;/p&gt;

  &lt;p&gt;Si necesitas devolver un resultado, procura que sea algo pequeño:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIKit&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;imageSizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;at&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;urls&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;CGSize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;urls&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;compactMap&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;autoreleasepool&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;UIImage&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;contentsOfFile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Si devuelves la imagen o el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Data&lt;/code&gt; grande, el pool no puede hacer magia: el valor sigue vivo en el scope exterior. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; libera temporales, no referencias fuertes que tú conservas.&lt;/p&gt;

  &lt;h2 id=&quot;lo-que-autoreleasepool-no-arregla&quot;&gt;Lo que autoreleasepool no arregla&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Un array que acumula todas las imágenes.&lt;/strong&gt; El array es una referencia fuerte; el pico es tuyo. El pool no reduce la memoria de algo que sigues reteniendo.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Un retain cycle.&lt;/strong&gt; El objeto no se libera nunca; el pool no rompe ciclos.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Una caché.&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIImage(named:)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NSCache&lt;/code&gt; y compañía retienen objetos a propósito.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Un pool alrededor de todo el bucle.&lt;/strong&gt; Se vacía demasiado tarde.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Código Swift puro.&lt;/strong&gt; Si no hay &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autorelease&lt;/code&gt;, no hay nada que drenar.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Un leak real de ImageIO o UIKit.&lt;/strong&gt; Si el pico sigue después del pool, necesitas el memory graph y Instruments.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;h2 id=&quot;resumen-cundo-utilizar-autoreleasepool&quot;&gt;Resumen: cuándo utilizar autoreleasepool&lt;/h2&gt;

  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Situación&lt;/th&gt;
        &lt;th&gt;Qué hacer&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td&gt;Bucle con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIImage&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NSImage&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NSAttributedString&lt;/code&gt; o similar&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; por iteración&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Modelo o struct Swift puro&lt;/td&gt;
        &lt;td&gt;Nada; ARC se encarga&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Array que retiene todos los resultados&lt;/td&gt;
        &lt;td&gt;Rediseña; el pool no reduce el pico&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Hilo propio largo&lt;/td&gt;
        &lt;td&gt;Pool al inicio y/o por iteración&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Retain cycle o caché&lt;/td&gt;
        &lt;td&gt;Memory graph; el pool no lo arregla&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Pico medido en Instruments&lt;/td&gt;
        &lt;td&gt;Prueba el pool y vuelve a medir&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;

  &lt;h2 id=&quot;cmo-comprobarlo&quot;&gt;Cómo comprobarlo&lt;/h2&gt;

  &lt;p&gt;Empieza por el informe de memoria de Xcode: te da la forma del pico y te dice si crece con el lote. Para saber quién lo causa, abre Instruments y usa el instrumento Allocations. Marca generaciones antes y después de una iteración o de un lote, y compara con y sin pool. Lo que buscas no es solo la memoria retenida al final, sino el pico transitorio que puede hacer que iOS termine la app.&lt;/p&gt;

  &lt;p&gt;Si quieres una prueba automática, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;XCTMemoryMetric&lt;/code&gt; mide el uso de memoria durante un bloque. Es útil para detectar regresiones de memoria retenida, pero para picos transitorios el instrumento Allocations es más directo. No pongas un umbral basado en una sola ejecución: la memoria varía entre dispositivos y versiones.&lt;/p&gt;

  &lt;p&gt;Y no optimices a ciegas. Crear y vaciar un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; tiene un pequeño coste. Por eso, úsalo cuando tengas muchos objetos temporales de Objective-C, no indiscriminadamente en cualquier función.&lt;/p&gt;

  &lt;h2 id=&quot;qudate-con-esta-idea&quot;&gt;Quédate con esta idea&lt;/h2&gt;

  &lt;p&gt;Swift ARC hace un gran trabajo gestionando la memoria, pero no sustituye al mecanismo de gestión de memoria de Objective-C.&lt;/p&gt;

  &lt;p&gt;Cuando un bucle crea muchos objetos temporales procedentes de APIs de Objective-C, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autoreleasepool&lt;/code&gt; te permite limitar cuánto tiempo permanecen acumulados en memoria.&lt;/p&gt;

  &lt;p&gt;La próxima vez que veas crecer el consumo de memoria durante un procesamiento por lotes, no añadas un pool a ciegas. Primero mide, comprueba qué objetos siguen vivos y busca posibles referencias fuertes. Si el problema está en los objetos autoreleased, un pool por iteración puede marcar la diferencia entre procesar miles de imágenes sin problemas y quedarte sin memoria.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2021/10216/&quot;&gt;ARC in Swift: Basics and beyond (WWDC21)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html&quot;&gt;Using Autorelease Pool Blocks&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/foundation/nsautoreleasepool&quot;&gt;NSAutoreleasePool&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/objectivec/autoreleasepool%28invoking:%29&quot;&gt;autoreleasepool(invoking:)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://forums.swift.org/t/the-role-of-autoreleasepool-in-swift-and-thoughts-about-memory-management-in-swift/52976&quot;&gt;The role of autoreleasepool in Swift (Swift Forums)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://forums.swift.org/t/is-autoreleasepool-still-needed-with-the-new-foundation/83224&quot;&gt;Is autoreleasepool still needed with the new Foundation? (Swift Forums)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://swiftrocks.com/autoreleasepool-in-swift&quot;&gt;autoreleasepool uses in Swift&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/xcode/gathering-information-about-memory-use&quot;&gt;Gathering information about memory use&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/xctest/xctmemorymetric&quot;&gt;XCTMemoryMetric&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">AttributedString: formato, enlaces y VoiceOver en SwiftUI</title>
    <link href="https://www.obocat.com/blog/2026/11/19/attributedstring-enlaces-voiceover/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/11/19/attributedstring-enlaces-voiceover/</id>
    <published>2026-11-19T08:00:00+00:00</published>
    <updated>2026-11-19T08:00:00+00:00</updated>
    <summary type="text">Cómo dar formato a un texto con AttributedString, gestionar enlaces con OpenURLAction y hacer que VoiceOver los reconozca como enlaces.</summary>
    
    <category term="iOS"/>
    
    <category term="SwiftUI"/>
    
    <category term="AttributedString"/>
    
    <category term="Accessibility"/>
    
    <category term="VoiceOver"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/11/19/attributedstring-enlaces-voiceover/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;Un párrafo con una negrita, una cursiva, un fragmento de código y dos enlaces parece un problema resuelto. Hasta que toca que VoiceOver lo lea como lo que es: texto con énfasis y enlaces, no una sola frase plana.&lt;/p&gt;

  &lt;p&gt;El problema no es solo pintar el texto. Un enlace tiene que seguir siéndolo cuando VoiceOver lo descubre, cuando cambia el tamaño de la letra o cuando el párrafo se combina con otros elementos.&lt;/p&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AttributedString&lt;/code&gt; no elimina toda la complejidad, pero junta las piezas en un solo valor. Y, sobre todo, permite que el formato tenga significado además de apariencia.&lt;/p&gt;

  &lt;h2 id=&quot;dos-capas-cmo-se-ve-y-qu-es&quot;&gt;Dos capas: cómo se ve y qué es&lt;/h2&gt;

  &lt;p&gt;El error clásico es tratar un enlace como texto azul con subrayado. Para los ojos, eso es un enlace. Para VoiceOver, no. Lo que convierte un fragmento en un enlace es el atributo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt;, no el color.&lt;/p&gt;

  &lt;p&gt;Lo mismo pasa con la negrita y la cursiva. Puedes pintar una palabra con una fuente concreta o puedes marcar que esa palabra está enfatizada. La primera opción cambia la apariencia; la segunda también puede cambiar cómo se interpreta el texto.&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SwiftUI&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ArticleText&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;content&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AttributedString&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AttributedString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;AttributedString permite mezclar formato, enlaces y semántica en un solo valor.&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;range&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;of&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;formato&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inlinePresentationIntent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stronglyEmphasized&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;range&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;of&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;enlaces&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;link&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;https://developer.apple.com/documentation/foundation/attributedstring&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;underlineStyle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;single&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;foregroundColor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accentColor&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;content&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;font&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accentColor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;cp&quot;&gt;#Preview {&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;ArticleText&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inlinePresentationIntent&lt;/code&gt; expresa la intención —énfasis fuerte, énfasis, código— y SwiftUI decide cómo representarla. Si necesitas una fuente concreta, puedes usar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.font&lt;/code&gt;, pero para texto de lectura conviene partir de estilos semánticos como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.body&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.headline&lt;/code&gt; para que Dynamic Type siga funcionando.&lt;/p&gt;

  &lt;p&gt;El atributo que no es negociable es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt;. El subrayado y el color ayudan a verlo, pero no lo convierten en un enlace. Si quitas &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt; y dejas solo el color azul, tendrás texto bonito y ningún enlace.&lt;/p&gt;

  &lt;figure class=&quot;post-figure&quot;&gt;
  &lt;img src=&quot;https://res.cloudinary.com/lo8bck4i/image/upload/v1794900926/blog/attributedstring/q7wgcesi4i6hqdkqmnyl.png&quot; alt=&quot;Captura de la app de ejemplo con el título AttributedString, texto formateado y un enlace subrayado.&quot; /&gt;
  &lt;figcaption&gt;Una vista de ejemplo con formato semántico y un enlace real, en un iPhone 15 Pro.&lt;/figcaption&gt;
&lt;/figure&gt;

  &lt;h2 id=&quot;markdown-como-punto-de-partida&quot;&gt;Markdown como punto de partida&lt;/h2&gt;

  &lt;p&gt;Si el texto ya viene en Markdown, no hace falta recorrer rangos a mano:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Foundation&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;makeMarkdown&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AttributedString&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;markdown&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;**Importante:** lee la [guía de AttributedString](https://developer.apple.com/documentation/foundation/attributedstring).&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;options&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AttributedString&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;MarkdownParsingOptions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;nv&quot;&gt;interpretedSyntax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inlineOnlyPreservingWhitespace&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AttributedString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;markdown&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;markdown&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inlineOnlyPreservingWhitespace&lt;/code&gt; interpreta el Markdown como texto en línea y conserva los saltos de línea. Es útil para párrafos que vienen de una API, una nota o un campo de texto.&lt;/p&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Text&lt;/code&gt; también acepta Markdown directamente en un string. La diferencia es que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AttributedString&lt;/code&gt; te deja el valor en la mano: puedes añadir atributos, cambiar un enlace, combinar varios fragmentos o pasarlo a otra capa antes de renderizarlo.&lt;/p&gt;

  &lt;h2 id=&quot;enlaces-que-se-comportan-como-enlaces&quot;&gt;Enlaces que se comportan como enlaces&lt;/h2&gt;

  &lt;p&gt;En SwiftUI, un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Text&lt;/code&gt; con un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AttributedString&lt;/code&gt; que contiene &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt; ya es interactivo. No necesitas un gesto sobre el texto ni calcular qué palabra se ha pulsado.&lt;/p&gt;

  &lt;p&gt;Si quieres decidir qué ocurre con algunos enlaces, usa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OpenURLAction&lt;/code&gt;:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SwiftUI&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;LinkHandlingView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AttributedString&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;environment&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(\&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;openURL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;OpenURLAction&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scheme&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;myapp&quot;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;systemAction&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

                &lt;span class=&quot;c1&quot;&gt;// Abre una pantalla interna o registra el evento.&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;handled&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.systemAction&lt;/code&gt; deja que el sistema abra el enlace: Safari, Mail, la app que corresponda.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.handled&lt;/code&gt; indica que ya lo has gestionado.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.discarded&lt;/code&gt; lo ignora.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;Para acciones internas, un esquema propio como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;myapp://glossary/attributedstring&lt;/code&gt; es suficiente. Para contenido web normal, deja que el sistema haga su trabajo. No conviertas todos los enlaces en acciones internas solo porque puedes.&lt;/p&gt;

  &lt;h2 id=&quot;voiceover-el-enlace-tiene-que-existir-en-el-rbol&quot;&gt;VoiceOver: el enlace tiene que existir en el árbol&lt;/h2&gt;

  &lt;p&gt;Cuando &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Text&lt;/code&gt; encuentra un fragmento con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt;, lo expone como un enlace. VoiceOver lo anuncia como tal y lo añade al rotor de enlaces. No hace falta añadir &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.accessibilityAddTraits(.isLink)&lt;/code&gt; al párrafo entero; de hecho, puede ser contraproducente.&lt;/p&gt;

  &lt;p&gt;Hay tres formas bastante habituales de romperlo:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Pintar el texto de azul y subrayarlo sin &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt;.&lt;/li&gt;
    &lt;li&gt;Usar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.onTapGesture&lt;/code&gt; sobre el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Text&lt;/code&gt; para abrir una pantalla.&lt;/li&gt;
    &lt;li&gt;Aplicar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.accessibilityElement(children: .combine)&lt;/code&gt; o un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.accessibilityLabel&lt;/code&gt; al párrafo completo.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;Las tres convierten el párrafo en una sola parada. Visualmente sigue pareciendo un enlace; para VoiceOver, ya no lo es.&lt;/p&gt;

  &lt;p&gt;El texto del enlace también importa. «Aquí» o «más información» no dicen nada fuera de contexto. «Guía de AttributedString» sí. VoiceOver permite recorrer los enlaces con el rotor; si todos se llaman «aquí», el rotor es inútil.&lt;/p&gt;

  &lt;p&gt;Prueba con el rotor de enlaces, no solo leyendo el párrafo de arriba abajo. En el simulador, activa VoiceOver o usa Accessibility Inspector. Comprueba que cada enlace aparece en el rotor, que el foco no se queda atrapado y que el orden coincide con el texto.&lt;/p&gt;

  &lt;h2 id=&quot;accesibilidad-cumplir-y-sobre-todo-no-obligar-a-reaprender&quot;&gt;Accesibilidad: cumplir y, sobre todo, no obligar a reaprender&lt;/h2&gt;

  &lt;p&gt;La accesibilidad tampoco es solo una decisión de producto. La Ley Europea de Accesibilidad (European Accessibility Act, EAA), la Directiva (UE) 2019/882, se aplica desde el 28 de junio de 2025. Si tu app entra en su ámbito —por ejemplo, porque ofrece o da acceso a comercio electrónico, banca, transporte de pasajeros, comunicaciones electrónicas o contenidos audiovisuales—, la accesibilidad pasa a ser un requisito legal, no un extra. Cada Estado miembro debe establecer sanciones efectivas, proporcionadas y disuasorias; la cuantía concreta depende de su transposición nacional. No todas las apps están cubiertas y hay exenciones, así que conviene revisar el ámbito antes de convertir esto en una promesa legal.&lt;/p&gt;

  &lt;p&gt;Pero el argumento práctico es anterior a la norma. Una persona que ya usa VoiceOver en su iPhone no debería aprender un modelo de interacción nuevo para tu app. Si los enlaces se comportan como enlaces, los botones como botones y los encabezados como encabezados, esa persona llega con parte del trabajo hecho. La app se siente predecible, el aprendizaje inicial es más corto y el soporte recibe menos preguntas del tipo «¿por qué esto no se puede activar?».&lt;/p&gt;

  &lt;p&gt;Hay un extra: una interfaz accesible también es una interfaz más legible para una máquina. Apple Intelligence y los agentes que interactúan con apps necesitan semántica: etiquetas, roles, valores y acciones. Si VoiceOver puede manejar tu app, es más probable que un agente de Apple Intelligence también lo haga. No es una garantía, pero una app que se explica bien a VoiceOver también se explica mejor a cualquier sistema que intente entenderla.&lt;/p&gt;

  &lt;p&gt;Eso no significa que la accesibilidad sea gratis. Significa que gran parte del valor está en usar las convenciones que el sistema ya ofrece, en lugar de inventar gestos o etiquetas que solo funcionan en tu pantalla. El rotor de enlaces y el foco son infraestructura compartida. Cuanto más se respetan, menos tiene que aprender quien ya conoce VoiceOver.&lt;/p&gt;

  &lt;p&gt;La accesibilidad también reduce el riesgo de que una función exista solo para quien ve la pantalla. Un enlace que solo es azul, un botón que solo responde a un tap o un estado que solo se comunica por color son deuda de accesibilidad.&lt;/p&gt;

  &lt;h2 id=&quot;la-decisin-prctica&quot;&gt;La decisión práctica&lt;/h2&gt;

  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Necesito&lt;/th&gt;
        &lt;th&gt;Uso&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td&gt;Varios enlaces dentro de un párrafo en SwiftUI&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AttributedString&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Text&lt;/code&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Decidir qué hace un enlace&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OpenURLAction&lt;/code&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Un enlace suelto y aislado&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Link&lt;/code&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Que VoiceOver lo reconozca&lt;/td&gt;
        &lt;td&gt;atributo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.link&lt;/code&gt;, no color ni subrayado&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;

  &lt;p&gt;El formato no es decoración. Un enlace es una promesa de navegación; si solo lo parece, la promesa se rompe para quien no lo ve. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AttributedString&lt;/code&gt; no es solo una API más cómoda: es una forma de que el texto lleve su significado consigo.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/foundation/attributedstring&quot;&gt;AttributedString&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/foundation/attributedstring/markdownparsingoptions&quot;&gt;AttributedString.MarkdownParsingOptions&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/text&quot;&gt;Text&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/openurlaction&quot;&gt;OpenURLAction&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/environmentvalues/openurl&quot;&gt;openURL&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/accessibility/voiceover&quot;&gt;VoiceOver&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/accessibility/accessibility-inspector&quot;&gt;Accessibility Inspector&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://commission.europa.eu/strategy-and-policy/policies/justice-and-fundamental-rights/disability/european-accessibility-act-eaa_en&quot;&gt;European Accessibility Act (EAA)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://eur-lex.europa.eu/eli/dir/2019/882/oj/eng&quot;&gt;Directive (EU) 2019/882&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://www.apple.com/apple-intelligence/&quot;&gt;Apple Intelligence&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">Sesión compartida entre iOS, widgets y Apple Watch: dónde encaja Keychain</title>
    <link href="https://www.obocat.com/blog/2026/11/16/sesion-compartida-widgets-apple-watch-keychain/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/11/16/sesion-compartida-widgets-apple-watch-keychain/</id>
    <published>2026-11-16T00:00:00+00:00</published>
    <updated>2026-11-16T00:00:00+00:00</updated>
    <summary type="text">Cómo mantener la sesión entre la app, widgets y Apple Watch con Keychain compartido, WatchConnectivity e iCloud Keychain.</summary>
    
    <category term="iOS"/>
    
    <category term="SwiftUI"/>
    
    <category term="WidgetKit"/>
    
    <category term="watchOS"/>
    
    <category term="Security"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/11/16/sesion-compartida-widgets-apple-watch-keychain/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;La escena se repite: alguien inicia sesión en la app, abre el widget y se encuentra con un «Inicia sesión». Levanta la muñeca y en el Apple Watch, más de lo mismo. La tentación es guardar el token en un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UserDefaults&lt;/code&gt; compartido y seguir adelante. Es cómodo, pero también es una mala idea: un token es una credencial y merece el mismo trato que una contraseña.&lt;/p&gt;

  &lt;p&gt;Keychain compartido ayuda, pero solo hasta cierto punto. Piensa en dos escenarios que se parecen y no son iguales: compartir un secreto &lt;strong&gt;dentro del mismo dispositivo&lt;/strong&gt; y moverlo &lt;strong&gt;de un dispositivo a otro&lt;/strong&gt;. Si los mezclas, acabas esperando magia del Keychain.&lt;/p&gt;

  &lt;h2 id=&quot;dos-problemas-distintos&quot;&gt;Dos problemas distintos&lt;/h2&gt;

  &lt;p&gt;La app y el widget viven en el mismo iPhone. Si ambos targets declaran el mismo &lt;em&gt;access group&lt;/em&gt;, pueden leer y escribir el mismo item de Keychain. En el reloj, la app del Watch y sus extensiones pueden hacer lo mismo.&lt;/p&gt;

  &lt;p&gt;El iPhone y el Apple Watch ya son otra historia. Son dispositivos distintos y un access group no sincroniza nada entre ellos. Para que la sesión llegue al reloj tienes dos caminos:&lt;/p&gt;

  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Necesidad&lt;/th&gt;
        &lt;th&gt;Mecanismo&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td&gt;App + widget en el mismo iPhone&lt;/td&gt;
        &lt;td&gt;Keychain access group&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;App + widgets/complicaciones en el Watch&lt;/td&gt;
        &lt;td&gt;Keychain access group en watchOS&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;iPhone ↔ Apple Watch&lt;/td&gt;
        &lt;td&gt;WatchConnectivity o iCloud Keychain&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;

  &lt;p&gt;En watchOS 9 o posterior, las complicaciones se construyen con WidgetKit; ClockKit está obsoleto. El mismo access group sirve para la app y sus extensiones de widget.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; Un Keychain access group comparte items en el mismo dispositivo. No los sincroniza entre el iPhone y el Watch.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Parece una diferencia menor, pero explica muchos fallos. Cuando el widget no encuentra el token, normalmente hay un entitlement mal puesto o un access group que no coincide. Cuando el que no lo encuentra es el Watch, a veces el código está bien: es que le estás pidiendo al Keychain algo que no puede hacer.&lt;/p&gt;

  &lt;h2 id=&quot;el-modelo-de-sesin&quot;&gt;El modelo de sesión&lt;/h2&gt;

  &lt;p&gt;Para el ejemplo nos basta con una estructura &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Codable&lt;/code&gt; pequeña:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Foundation&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Security&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Codable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Equatable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Sendable&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;accessToken&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;expiresAt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Date&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;enum&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionStoreError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Error&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;unexpectedStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;OSStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;invalidData&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;En este ejemplo, el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;refreshToken&lt;/code&gt; no está en el modelo compartido. La app lo guarda en un Keychain privado y el widget y el reloj solo reciben el token de acceso, que es lo que necesitan para pintar datos y hablar con la API. Es la opción de mínimo privilegio, no una prohibición absoluta: si prefieres que el reloj refresque por su cuenta, puedes compartir el mismo refresh token. En ese caso, no lo pongas en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;applicationContext&lt;/code&gt;; envíalo con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sendMessage&lt;/code&gt; y guárdalo en el Keychain del reloj. El logout debe revocar el refresh token en el servidor siempre, compartas el token o no.&lt;/p&gt;

  &lt;p&gt;Ese tipo y el store que viene después tienen que estar disponibles en la app y en la extensión. Puedes compartirlos con un framework interno o añadir los mismos archivos a los dos targets.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; El &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UserDefaults&lt;/code&gt; de un App Group es cómodo para un identificador de usuario, una fecha de última sincronización o un flag de onboarding. No es el sitio para tokens, credenciales ni secretos.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;keychain-compartido-entre-la-app-y-el-widget&quot;&gt;Keychain compartido entre la app y el widget&lt;/h2&gt;

  &lt;p&gt;Lo primero es habilitar &lt;strong&gt;Keychain Sharing&lt;/strong&gt; en la app y en la extensión del widget. En Xcode, añade la capability a los dos targets y apunta al mismo grupo. En los entitlements debería quedar algo así:&lt;/p&gt;

  &lt;div class=&quot;language-xml highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nt&quot;&gt;&amp;lt;key&amp;gt;&lt;/span&gt;keychain-access-groups&lt;span class=&quot;nt&quot;&gt;&amp;lt;/key&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;array&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;string&amp;gt;&lt;/span&gt;$(AppIdentifierPrefix)com.example.shared&lt;span class=&quot;nt&quot;&gt;&amp;lt;/string&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/array&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Ojo con el valor que se usa en tiempo de ejecución: Xcode sustituye &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;$(AppIdentifierPrefix)&lt;/code&gt; al compilar, así que el grupo ya lleva el Team ID. Si tu Team ID es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ABCDE12345&lt;/code&gt;, el grupo real es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ABCDE12345.com.example.shared&lt;/code&gt;. Si pasas el grupo sin prefijo, el Keychain no lo encuentra y puede devolver &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;errSecMissingEntitlement&lt;/code&gt;. En el código puedes centralizarlo en una constante; en producción, mejor inyecta el valor desde el Info.plist con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;$(AppIdentifierPrefix)com.example.shared&lt;/code&gt; y léelo con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Bundle.main&lt;/code&gt;.&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// Este store solo guarda el token de acceso.&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// El refreshToken vive en un grupo privado de la app.&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SharedSessionStore&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;service&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;com.example.session&quot;&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;account&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;current&quot;&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;accessGroup&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;ABCDE12345.com.example.shared&quot;&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;baseQuery&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecClass&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSecClassGenericPassword&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecAttrService&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecAttrAccount&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;account&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecAttrAccessGroup&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accessGroup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecAttrSynchronizable&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;save&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;JSONEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;attributes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecValueData&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kSecAttrAccessible&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SecItemUpdate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;baseQuery&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CFDictionary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attributes&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CFDictionary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecItemNotFound&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;baseQuery&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;attributes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;forEach&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;$0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

            &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;addStatus&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SecItemAdd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CFDictionary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;addStatus&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecSuccess&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionStoreError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unexpectedStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;addStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecSuccess&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionStoreError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unexpectedStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;status&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;load&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;query&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;baseQuery&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kSecReturnData&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kSecMatchLimit&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSecMatchLimitOne&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CFTypeRef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SecItemCopyMatching&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;query&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CFDictionary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecItemNotFound&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecSuccess&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionStoreError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unexpectedStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;status&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as?&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Data&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionStoreError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;invalidData&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;JSONDecoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Session&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;delete&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SecItemDelete&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;baseQuery&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CFDictionary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecSuccess&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errSecItemNotFound&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionStoreError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unexpectedStatus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;status&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Dos detalles marcan la diferencia:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrAccessGroup&lt;/code&gt; hace que la app y el widget lean el mismo item. Sin ese atributo, cada proceso busca en su propio espacio.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly&lt;/code&gt; permite leer el token después del primer desbloqueo, que es lo que necesita un widget en segundo plano. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;WhenUnlocked&lt;/code&gt; falla cuando el dispositivo está bloqueado, y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ThisDeviceOnly&lt;/code&gt; evita que el item se sincronice con iCloud.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; Para un widget, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrAccessibleWhenUnlocked&lt;/code&gt; no es una buena opción. Si la extensión se ejecuta con el dispositivo bloqueado, la lectura puede fallar con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;errSecInteractionNotAllowed&lt;/code&gt;. Usa una clase accesible después del primer desbloqueo y no dependas de que el usuario tenga la pantalla desbloqueada.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;El otro detalle es de seguridad: este &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Session&lt;/code&gt; solo contiene el token de acceso. El &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;refreshToken&lt;/code&gt; se queda en un Keychain privado de la app. Si el reloj necesita refrescar por su cuenta, puedes compartir el mismo refresh token, pero envíalo solo por &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sendMessage&lt;/code&gt;, guárdalo en el Keychain del reloj y revócalo en el servidor al cerrar sesión.&lt;/p&gt;

  &lt;h2 id=&quot;el-widget-lee-la-app-refresca&quot;&gt;El widget lee, la app refresca&lt;/h2&gt;

  &lt;p&gt;El widget no debería renovar el token. Los timelines se ejecutan cuando el sistema lo decide, pueden solaparse y no tienen una persona delante para resolver un login. Si el token caduca, el widget enseña un estado sin sesión o datos en caché; la app es la que refresca y actualiza el Keychain.&lt;/p&gt;

  &lt;p&gt;Un provider sencillo puede leer la sesión compartida así:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;WidgetKit&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;TimelineEntry&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Date&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionProvider&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;TimelineProvider&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;placeholder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;now&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;preview&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getSnapshot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;@escaping&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Void&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;entry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getTimeline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;@escaping&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Timeline&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Void&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;next&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Calendar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;byAdding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;minute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;now&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Timeline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;entries&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;entry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;policy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;after&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;entry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;session&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SharedSessionStore&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;load&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionEntry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;now&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Cuando la app inicia sesión, la cierra o renueva el token, pide a WidgetKit que vuelva a cargar los timelines:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;WidgetKit&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;WidgetCenter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shared&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reloadAllTimelines&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Parece un detalle menor, pero evita esa sensación de que el widget «no se entera» del login. El Keychain no avisa a nadie: si quieres que el widget se actualice, tienes que decírselo.&lt;/p&gt;

  &lt;h2 id=&quot;apple-watch-el-keychain-no-cruza-solo&quot;&gt;Apple Watch: el Keychain no cruza solo&lt;/h2&gt;

  &lt;p&gt;La app del Watch tiene su propio Keychain. Puede compartirlo con sus extensiones y widgets/complicaciones mediante un access group de watchOS, pero ese grupo no es el mismo almacén que el del iPhone. Aunque el identificador sea idéntico en los entitlements, los items viven en dispositivos distintos.&lt;/p&gt;

  &lt;p&gt;Para que la app del Watch use un access group, añade Keychain Sharing al target del Watch y a sus extensiones. Sin esa capability, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrAccessGroup&lt;/code&gt; falla con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;errSecMissingEntitlement&lt;/code&gt;, también cuando el token llega por WatchConnectivity.&lt;/p&gt;

  &lt;p&gt;En la práctica, tienes dos estrategias válidas.&lt;/p&gt;

  &lt;h3 id=&quot;opcin-1-watchconnectivity&quot;&gt;Opción 1: WatchConnectivity&lt;/h3&gt;

  &lt;p&gt;Para una app companion, es la opción más directa. La app del iPhone envía la sesión al reloj y la app del Watch la guarda en su Keychain. No depende de iCloud Keychain y te deja decidir cuándo se envía y qué se envía.&lt;/p&gt;

  &lt;p&gt;Usa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;updateApplicationContext&lt;/code&gt; para mantener el último estado y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sendMessage&lt;/code&gt; para entregarlo cuanto antes si el reloj está accesible. Activa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;WCSession&lt;/code&gt; lo antes posible y trátala como un canal con entrega diferida: el sistema decide cuándo despertar al reloj. Para una sesión que cambia poco, el contexto suele bastar; para una acción interactiva, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sendMessage&lt;/code&gt; reduce la espera.&lt;/p&gt;

  &lt;h3 id=&quot;opcin-2-icloud-keychain&quot;&gt;Opción 2: iCloud Keychain&lt;/h3&gt;

  &lt;p&gt;Si necesitas que la sesión llegue al Watch sin una app companion, o quieres cubrir Family Setup, Apple plantea la sincronización de iCloud Keychain como opción. Conviene probarlo en un dispositivo real antes de depender de ello, sobre todo en Family Setup. El cambio clave es guardar el item con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrSynchronizable&lt;/code&gt; a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;baseQuery&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kSecClass&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSecClassGenericPassword&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kSecAttrService&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kSecAttrAccount&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;account&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kSecAttrAccessGroup&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accessGroup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kSecAttrSynchronizable&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;attributes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;kSecValueData&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;kSecAttrAccessible&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSecAttrAccessibleAfterFirstUnlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;kSecAttrSynchronizable&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Si el item ya existe con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrSynchronizable&lt;/code&gt; a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, una consulta con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; no lo encontrará. Para migrar, lee con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kSecAttrSynchronizableAny&lt;/code&gt;, guarda el item con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; y borra el antiguo. No cambies el atributo del item existente a ciegas.&lt;/p&gt;

  &lt;p&gt;También hay que añadir la capability de Keychain Sharing al target del Watch que vaya a leer el item. A partir de ahí, iCloud Keychain se encarga de sincronizarlo entre los dispositivos de la misma cuenta, cuando puede.&lt;/p&gt;

  &lt;p&gt;Lo bueno es que no necesitas mantener una sesión de WatchConnectivity ni que el iPhone esté cerca. Pero hay límites que hay que asumir desde el principio:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;El usuario puede desactivar iCloud Keychain.&lt;/li&gt;
    &lt;li&gt;No está disponible en todas las regiones.&lt;/li&gt;
    &lt;li&gt;La sincronización no es inmediata; depende de red, batería y condiciones del sistema.&lt;/li&gt;
    &lt;li&gt;No puedes usar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ThisDeviceOnly&lt;/code&gt;, porque precisamente quieres que el item salga del dispositivo.&lt;/li&gt;
    &lt;li&gt;Estás sincronizando un access token con todos los dispositivos de la cuenta.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ThisDeviceOnly&lt;/code&gt; e iCloud Keychain son incompatibles para este caso. Si necesitas sincronización, la accesibilidad debe permitirla; si necesitas que el token no salga del dispositivo, usa WatchConnectivity.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h3 id=&quot;si-compartes-el-mismo-refresh-token&quot;&gt;Si compartes el mismo refresh token&lt;/h3&gt;

  &lt;p&gt;No hacen falta tokens por dispositivo. Puedes dar al reloj el mismo refresh token que usa el iPhone. La revocación en servidor es obligatoria en cualquier logout, compartas el token o no; si lo compartes, además es lo que corta el acceso del reloj. Dicho eso, cuida estos puntos:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;No lo persistas en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;applicationContext&lt;/code&gt;:&lt;/strong&gt; ese contexto puede sobrevivir en el dispositivo. Envía el refresh token con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sendMessage&lt;/code&gt; y guárdalo en el Keychain del reloj. El &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;applicationContext&lt;/code&gt; puede seguir llevando solo el access token.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Asume la ventana de exposición:&lt;/strong&gt; si el token se filtra antes del logout, el servidor lo aceptará hasta que lo revoques. La revocación reduce la ventana, no la elimina.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Rota el token y detecta la reutilización:&lt;/strong&gt; si el mismo refresh token se usa en iPhone y reloj, una rotación mal llevada puede invalidar al otro. Decide qué proceso renueva y cómo se propaga el token nuevo.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;Al cerrar sesión, revoca el refresh token en el servidor, borra los tokens locales del iPhone, el widget y el reloj, y envía el mensaje de cierre al reloj.&lt;/p&gt;

  &lt;p&gt;El modelo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Session&lt;/code&gt; de arriba mantiene el refresh token fuera del objeto compartido para que el caso base sea el más restrictivo. Si adoptas esta variante, añade el refresh token al payload de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sendMessage&lt;/code&gt; y al store del reloj; no lo añadas al payload de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;updateApplicationContext&lt;/code&gt;.&lt;/p&gt;

  &lt;h2 id=&quot;login-refresco-y-logout&quot;&gt;Login, refresco y logout&lt;/h2&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; Revocar el refresh token en el servidor no es opcional. Borrarlo del iPhone, del widget o del reloj no lo invalida. Si el refresh token sigue vivo, cualquiera que lo tenga puede seguir renovando la sesión. Hazlo siempre, compartas el token con el reloj o no.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Con estas piezas, el ciclo de vida queda bastante limpio. Después de un login correcto:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Guarda la sesión en el Keychain compartido.&lt;/li&gt;
    &lt;li&gt;Recarga los timelines del widget.&lt;/li&gt;
    &lt;li&gt;Envía la sesión al Watch si existe una app companion.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;Cuando renueves el token, actualiza el item y repite los pasos 2 y 3. Cuando el usuario cierre sesión, revoca el refresh token en el servidor, borra el item, recarga los widgets y envía un mensaje al Apple Watch. Si el reloj comparte el mismo refresh token, la revocación en servidor también lo cubre.&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;WidgetKit&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SessionCoordinator&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didSignIn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SharedSessionStore&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;save&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;WidgetCenter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shared&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reloadAllTimelines&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Envía la sesión al Watch con WatchConnectivity.&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didSignOut&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Revoca el refresh token en el servidor.&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SharedSessionStore&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;delete&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;WidgetCenter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shared&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reloadAllTimelines&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Envía el cierre de sesión al Watch con WatchConnectivity.&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Hay una regla que ahorra muchos problemas: &lt;strong&gt;un solo proceso renueva el token&lt;/strong&gt;. Si la app, el widget y el reloj intentan refrescar a la vez, puedes rotar el token varias veces y dejar a alguno con una credencial invalidada. En una app companion, la app del iPhone renueva y distribuye.&lt;/p&gt;

  &lt;p&gt;La revocación del refresh token impide renovar, pero no invalida automáticamente el access token que ya está en circulación. Para cerrar esa ventana, usa access tokens cortos o una lista de revocación en el servidor.&lt;/p&gt;

  &lt;h2 id=&quot;la-decisin-prctica&quot;&gt;La decisión práctica&lt;/h2&gt;

  &lt;p&gt;Si tu app tiene widget y una app companion para Apple Watch, yo empezaría por esta combinación:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Keychain access group para la app y el widget en el iPhone.&lt;/li&gt;
    &lt;li&gt;Keychain access group en watchOS para la app del reloj y sus extensiones.&lt;/li&gt;
    &lt;li&gt;WatchConnectivity para llevar la sesión del iPhone al Watch.&lt;/li&gt;
    &lt;li&gt;iCloud Keychain solo si necesitas sincronización sin companion o Family Setup, asumiendo sus límites.&lt;/li&gt;
    &lt;li&gt;Revocación en servidor del refresh token al cerrar sesión.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;Keychain compartido no lo resuelve todo por sí solo. Es una pieza excelente para compartir secretos dentro del mismo dispositivo. Para cruzar de un dispositivo a otro, la sesión se transfiere o se sincroniza, y cada opción tiene un coste distinto en seguridad, latencia y complejidad.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/security/sharing-access-to-keychain-items-among-a-collection-of-apps&quot;&gt;Sharing access to keychain items among a collection of apps&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/security/keychain-services&quot;&gt;Keychain Services&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/security/ksecattrsynchronizable&quot;&gt;kSecAttrSynchronizable&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc7009&quot;&gt;OAuth 2.0 Token Revocation (RFC 7009)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/watchconnectivity/wcsession&quot;&gt;WCSession&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/widgetkit&quot;&gt;WidgetKit&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2021/10003/&quot;&gt;There and back again: Data transfer on Apple Watch&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">ViewBuilder y applyIf: el coste oculto de una condición en SwiftUI</title>
    <link href="https://www.obocat.com/blog/2026/11/12/viewbuilder-identidad-condicional-swiftui/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/11/12/viewbuilder-identidad-condicional-swiftui/</id>
    <published>2026-11-12T00:00:00+00:00</published>
    <updated>2026-11-12T00:00:00+00:00</updated>
    <summary type="text">Por qué un if dentro de @ViewBuilder cambia la identidad estructural de la vista y reinicia su estado.</summary>
    
    <category term="iOS"/>
    
    <category term="SwiftUI"/>
    
    <category term="ViewBuilder"/>
    
    <category term="State"/>
    
    <category term="Architecture"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/11/12/viewbuilder-identidad-condicional-swiftui/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;Hay un helper que aparece una y otra vez en proyectos SwiftUI:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@ViewBuilder&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;applyIf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Content&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;condition&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;nv&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;Self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Content&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;condition&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;La intención es buena: aplicar un modificador solo cuando se cumple una condición. Compila, es cómodo y parece inocuo. Pero no lo es del todo.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; El problema no es que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;applyIf&lt;/code&gt; no compile, sino que cada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; crea dos ramas con identidad propia. Al alternar la condición, SwiftUI destruye el estado de la vista.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;lo-que-realmente-construye-viewbuilder&quot;&gt;Lo que realmente construye ViewBuilder&lt;/h2&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@ViewBuilder&lt;/code&gt; no es solo azúcar sintáctico para elegir una vista u otra. Es un result builder: transforma el cuerpo de la función en una estructura de tipos.&lt;/p&gt;

  &lt;p&gt;Cuando usamos el helper de esta forma:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;MyView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;applyIf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;nv&quot;&gt;$0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;el compilador genera algo equivalente a:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;_ConditionalContent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Content&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;Self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_ConditionalContent&lt;/code&gt; es un tipo interno de SwiftUI que representa dos ramas posibles. En el ejemplo, una rama contiene la vista modificada y la otra contiene la vista original:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;_ConditionalContent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;ModifiedContent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;MyView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_BackgroundStyleModifier&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;MyView&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; Lo importante es entender que el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; no se evalúa como una condición dentro de un mismo modificador: la vista resultante tiene dos identidades estructurales posibles.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;identidad-estructural-no-solo-valores&quot;&gt;Identidad estructural, no solo valores&lt;/h2&gt;

  &lt;p&gt;SwiftUI distingue entre el valor de una vista y su identidad en la jerarquía. La identidad estructural depende del tipo y de la posición de la vista en el árbol. Un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if/else&lt;/code&gt; dentro de un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ViewBuilder&lt;/code&gt; crea dos posiciones distintas: la rama verdadera y la falsa.&lt;/p&gt;

  &lt;p&gt;Cuando &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;condition&lt;/code&gt; cambia, SwiftUI no está cambiando el parámetro de un mismo modificador. Está eliminando una rama e insertando la otra. Si hay una animación, el resultado es una transición —por ejemplo, un fade— en lugar de una interpolación entre los dos valores.&lt;/p&gt;

  &lt;p&gt;Eso también afecta al estado. SwiftUI asocia &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@State&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@StateObject&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@FocusState&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@GestureState&lt;/code&gt; al ciclo de vida y a la identidad de la vista. Si la vista cambia de rama, su almacenamiento desaparece y vuelve a inicializarse.&lt;/p&gt;

  &lt;p&gt;Con el helper definido arriba, el ejemplo se puede probar directamente en un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;#Preview&lt;/code&gt;:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Stateful&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@State&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;TextField&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;err&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;textFieldStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roundedBorder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Bool&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;Stateful&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;applyIf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;nv&quot;&gt;$0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;red&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SamplePreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@State&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isEnabled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;VStack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;spacing&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;24&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;Sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

            &lt;span class=&quot;kt&quot;&gt;Button&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;toggle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Disable applyIf&quot;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Enable applyIf&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fontWeight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;semibold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;frame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;maxWidth&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;infinity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;foregroundStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;white&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clipShape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;RoundedRectangle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;cornerRadius&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

            &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;isEnabled: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;description&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;font&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;caption&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;foregroundStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;secondary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;cp&quot;&gt;#Preview {&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;SamplePreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Al alternar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;isEnabled&lt;/code&gt;, el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TextField&lt;/code&gt; pierde el texto que el usuario había escrito. Lo mismo ocurre con un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@StateObject&lt;/code&gt; que se cree dentro de la vista condicional. No es que SwiftUI borre el estado porque sí: para SwiftUI, la vista ha cambiado de posición en el árbol.&lt;/p&gt;

  &lt;p&gt;Hay un matiz importante: si el estado vive en un padre que no cambia de identidad, sobrevive. El problema afecta al estado que pertenece a la vista que cambia de rama.&lt;/p&gt;

  &lt;h2 id=&quot;cmo-mantener-la-identidad&quot;&gt;Cómo mantener la identidad&lt;/h2&gt;

  &lt;p&gt;La regla práctica es: si las dos ramas representan la misma vista con una configuración distinta, intenta mantener un único tipo y cambia solo el valor.&lt;/p&gt;

  &lt;p&gt;Cuando el modificador acepta un valor condicional, es la opción más directa:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;MyView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;red&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;MyView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;frame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;MyView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;opacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;También puedes encapsular la condición en un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ViewModifier&lt;/code&gt; estable:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ConditionalBackground&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ViewModifier&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Bool&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;content&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Content&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;content&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;red&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conditionalBackground&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;modifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;ConditionalBackground&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;isEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; El tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ModifiedContent&amp;lt;MyView, ConditionalBackground&amp;gt;&lt;/code&gt; no cambia; el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Bool&lt;/code&gt; es solo un parámetro. La identidad se mantiene y el modificador se sigue aplicando siempre.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;cundo-s-usar-un-if&quot;&gt;Cuándo sí usar un if&lt;/h2&gt;

  &lt;p&gt;No se trata de prohibir &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;applyIf&lt;/code&gt; o los &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ViewBuilder&lt;/code&gt;. Las ramas son la herramienta correcta cuando realmente queremos dos estructuras distintas: mostrar una pantalla de carga o el contenido, un estado vacío o una lista, una vista u otra.&lt;/p&gt;

  &lt;p&gt;La clave es elegir conscientemente:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Si quieres cambiar la estructura, usa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if/else&lt;/code&gt; y asume que la identidad cambia.&lt;/li&gt;
    &lt;li&gt;Si quieres cambiar solo una propiedad de la misma vista, mantén la identidad y pasa el valor al modificador.&lt;/li&gt;
    &lt;li&gt;Si el estado debe sobrevivir a un cambio estructural, súbelo a un padre estable o a un modelo que no se destruya.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;h2 id=&quot;conclusin&quot;&gt;Conclusión&lt;/h2&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;applyIf&lt;/code&gt; es cómodo, pero esconde una decisión de arquitectura: cada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; en un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ViewBuilder&lt;/code&gt; crea dos ramas con identidad propia. Eso reinicia el estado de la vista que cambia de rama.&lt;/p&gt;

  &lt;p&gt;Antes de añadir un helper condicional, merece la pena preguntarse si las dos ramas son realmente dos vistas distintas o la misma vista con una configuración diferente. Si es lo segundo, mantener el tipo estable es la opción más predecible.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/viewbuilder&quot;&gt;ViewBuilder&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2021/10022&quot;&gt;Demystify SwiftUI (WWDC21)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://www.objc.io/blog/2021/08/24/conditional-view-modifiers&quot;&gt;Why Conditional View Modifiers are a Bad Idea&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://swiftwithmajid.com/2021/12/09/structural-identity-in-swiftui&quot;&gt;Structural identity in SwiftUI&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">SF Symbols personalizados: color y animación más allá del catálogo</title>
    <link href="https://www.obocat.com/blog/2026/11/09/sf-symbols-personalizados-color-animacion/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/11/09/sf-symbols-personalizados-color-animacion/</id>
    <published>2026-11-09T00:00:00+00:00</published>
    <updated>2026-11-09T00:00:00+00:00</updated>
    <summary type="text">Los SF Symbols personalizados no son iconos estáticos: con las anotaciones correctas heredan los modos de color y las animaciones del sistema.</summary>
    
    <category term="iOS"/>
    
    <category term="SwiftUI"/>
    
    <category term="SF Symbols"/>
    
    <category term="Design"/>
    
    <category term="Accessibility"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/11/09/sf-symbols-personalizados-color-animacion/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;Hay una idea bastante extendida entre desarrolladores y diseñadores: los SF Symbols son el catálogo de iconos que Apple incluye en el sistema, y si necesitas algo distinto, toca dibujar un PNG o un PDF y olvidarte de las ventajas. No es así.&lt;/p&gt;

  &lt;p&gt;Los SF Symbols personalizados existen desde hace varias versiones. No son imágenes normales: son plantillas vectoriales que se comportan como símbolos del sistema. Si las preparas bien, pueden usar los mismos modos de color y la misma familia de animaciones que los iconos de Apple.&lt;/p&gt;

  &lt;p&gt;La diferencia importante está en una palabra: &lt;strong&gt;anotaciones&lt;/strong&gt;. Un SVG bonito no basta. El símbolo necesita capas y metadatos para que SwiftUI sepa qué partes colorear, qué orden seguir y qué animar.&lt;/p&gt;

  &lt;h2 id=&quot;qu-es-realmente-un-sf-symbol-personalizado&quot;&gt;Qué es realmente un SF Symbol personalizado&lt;/h2&gt;

  &lt;p&gt;Un SF Symbol personalizado es un SVG validado por la app SF Symbols y añadido a un asset catalog como &lt;strong&gt;Symbol Image Set&lt;/strong&gt;, no como un image set normal. Esa distinción importa: si lo metes como una imagen corriente, pierdes el comportamiento de símbolo.&lt;/p&gt;

  &lt;p&gt;El flujo habitual es:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Buscar en la app SF Symbols un símbolo parecido y usar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;File &amp;gt; Duplicate as Custom Symbol&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;File &amp;gt; Export Template&lt;/code&gt;.&lt;/li&gt;
    &lt;li&gt;Editar el SVG en una herramienta vectorial. Convierte trazos a paths, usa rellenos planos y evita sombras, efectos y paths ocultos.&lt;/li&gt;
    &lt;li&gt;Importar el SVG de vuelta en la app SF Symbols y validarlo.&lt;/li&gt;
    &lt;li&gt;Anotar los modos de renderizado y, si hace falta, las animaciones.&lt;/li&gt;
    &lt;li&gt;Exportar el símbolo y añadirlo al asset catalog como Symbol Image Set.&lt;/li&gt;
    &lt;li&gt;Usarlo con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Image(&quot;custom.orbit&quot;)&lt;/code&gt;, no con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Image(systemName:)&lt;/code&gt;.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;La app SF Symbols es la que valida que el SVG cumple el formato. También es donde se guardan las anotaciones.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; Si exportas una plantilla para editarla, esa exportación &lt;strong&gt;no incluye&lt;/strong&gt; las anotaciones. Para conservarlas, hay que arrastrar el SVG editado sobre el símbolo existente.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;de-un-svg-normal-a-un-sf-symbol&quot;&gt;De un SVG normal a un SF Symbol&lt;/h2&gt;

  &lt;p&gt;La app SF Symbols espera una plantilla con una estructura muy concreta. Si ya tienes el icono dibujado en SVG, no hace falta redibujarlo desde cero: hay herramientas que generan el envoltorio de símbolo a partir de un SVG convencional.&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://github.com/jaywcjlove/create-custom-symbols&quot;&gt;&lt;strong&gt;Create Custom Symbols&lt;/strong&gt;&lt;/a&gt;: app de macOS para arrastrar uno o varios SVG y exportar un archivo que puedes importar en la app SF Symbols. Es útil para lotes y para convertir iconos que ya existen en el diseño.&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://github.com/swhitty/SwiftDraw&quot;&gt;&lt;strong&gt;SwiftDraw&lt;/strong&gt;&lt;/a&gt;: herramienta de línea de comandos. Con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;brew install swiftdraw&lt;/code&gt;, puedes ejecutar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;swiftdraw icon.svg --format sfsymbol&lt;/code&gt;. Expande trazos, ajusta el winding de los paths y alinea el resultado para que Xcode lo acepte.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Plugins de Figma&lt;/strong&gt; como &lt;a href=&quot;https://www.figma.com/community/plugin/1487107089082698461/sf-symbol-generator&quot;&gt;&lt;strong&gt;SF Symbol Generator&lt;/strong&gt;&lt;/a&gt; y &lt;a href=&quot;https://www.figma.com/community/plugin/1265484574589944515/sf-symbols-optimizer&quot;&gt;&lt;strong&gt;SF Symbols Optimizer&lt;/strong&gt;&lt;/a&gt;: exportan iconos de Figma como SVG de SF Symbols, con variantes estáticas o variables.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; Estas herramientas ahorran el trabajo de estructura, no el de diseño. No pueden adivinar qué capas deben formar parte de una jerarquía, qué colores van en palette o qué partes deben animarse.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Los SVG convencionales suelen traer trazos, máscaras, compound paths o grupos anidados que no siempre se convierten bien. Revisa el resultado en la app SF Symbols, comprueba la dirección de los paths y anota las capas antes de darlo por bueno.&lt;/p&gt;

  &lt;h2 id=&quot;color-cuatro-modos-no-uno&quot;&gt;Color: cuatro modos, no uno&lt;/h2&gt;

  &lt;p&gt;Para que los ejemplos se puedan probar sin crear un asset, uso símbolos del sistema. Los modificadores son los mismos; solo cambia cómo se carga la imagen. Cuando tengas el tuyo, sustituye &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Image(systemName: &quot;sparkles&quot;)&lt;/code&gt; por &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Image(&quot;tu.simbolo&quot;)&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;Los símbolos del sistema pueden renderizarse en cuatro modos. Los personalizados también, siempre que sus capas estén anotadas:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Monochrome:&lt;/strong&gt; un solo color para todas las capas.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Hierarchical:&lt;/strong&gt; un color con distintos niveles de opacidad para dar profundidad.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Palette:&lt;/strong&gt; un color por capa o grupo de capas.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Multicolor:&lt;/strong&gt; colores intrínsecos definidos en el propio símbolo.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;En SwiftUI se elige con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;symbolRenderingMode&lt;/code&gt;:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sparkles&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;font&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;system&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;72&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolRenderingMode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;foregroundStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cyan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;La parte importante no es el modificador, sino lo que hay detrás. Para que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.palette&lt;/code&gt; funcione, el símbolo tiene que tener capas anotadas para palette; los colores se pasan desde &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foregroundStyle&lt;/code&gt;. Para que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.hierarchical&lt;/code&gt; tenga sentido, necesita grupos primario, secundario y terciario. Si no hay anotaciones, el resultado puede ser más plano de lo que esperabas.&lt;/p&gt;

  &lt;p&gt;En SF Symbols 7 también existe el renderizado con gradiente, disponible en todos los modos de color y aplicable a símbolos personalizados. Es un recurso útil para dar profundidad, pero conviene usarlo con moderación: un icono de barra de herramientas no necesita el mismo tratamiento que una ilustración a gran tamaño.&lt;/p&gt;

  &lt;p&gt;También conviene usar colores semánticos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.primary&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.tint&lt;/code&gt;, colores del asset catalog) en lugar de valores fijos. Así el símbolo sigue funcionando en modo oscuro, con vibrancy y con los ajustes de accesibilidad.&lt;/p&gt;

  &lt;h2 id=&quot;animacin-el-mismo-sistema-con-matices&quot;&gt;Animación: el mismo sistema, con matices&lt;/h2&gt;

  &lt;p&gt;Desde iOS 17, los símbolos tienen efectos universales: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bounce&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pulse&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;variableColor&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scale&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;appear&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;disappear&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;replace&lt;/code&gt;. Las versiones posteriores añadieron &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;wiggle&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rotate&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;breathe&lt;/code&gt; y, en SF Symbols 7, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;drawOn&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;drawOff&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;La buena noticia es que estos efectos también se pueden aplicar a símbolos personalizados. La matización es que los efectos que dependen de capas —como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;variableColor&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;drawOn&lt;/code&gt;— necesitan que el símbolo tenga esas capas y esté anotado. Un símbolo antiguo o mal preparado puede caer en un fade genérico en lugar de hacer la animación que esperabas.&lt;/p&gt;

  &lt;p&gt;Un ejemplo mínimo en SwiftUI:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CustomSymbolDemo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@State&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;bounceTrigger&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@State&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isPulsing&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;VStack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;spacing&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sparkles&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;font&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;system&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;88&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolRenderingMode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hierarchical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolEffect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bounce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bounceTrigger&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolEffect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pulse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isActive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;isPulsing&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;accessibilityLabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Highlight&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

            &lt;span class=&quot;kt&quot;&gt;HStack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;spacing&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;kt&quot;&gt;Button&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Bounce&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;bounceTrigger&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

                &lt;span class=&quot;kt&quot;&gt;Button&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isPulsing&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Stop pulse&quot;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Pulse&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;isPulsing&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;toggle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;cp&quot;&gt;#Preview {&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;CustomSymbolDemo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;value:&lt;/code&gt; se usa para efectos discretos que se disparan cuando cambia un valor. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;isActive:&lt;/code&gt; se usa para efectos indefinidos que siguen activos mientras la condición sea verdadera. También puedes ajustar la repetición o la velocidad con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;options&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;La app SF Symbols permite copiar la configuración de un efecto con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Copy Configuration&lt;/code&gt;. Es una forma cómoda de pasar del preview al código sin adivinar qué combinación de opciones estabas viendo.&lt;/p&gt;

  &lt;p&gt;Para &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;variableColor&lt;/code&gt;, el símbolo necesita varias capas y una anotación de variable color. Un ejemplo típico es una batería o una barra de progreso:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BatterySymbol&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;level&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Double&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;battery.75&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolRenderingMode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;foregroundStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;green&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;yellow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolEffect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;variableColor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;level&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;No todos los símbolos personalizados tienen que soportar todo. Lo sano es probar cada efecto en la app SF Symbols antes de llevarlo al código.&lt;/p&gt;

  &lt;h2 id=&quot;lo-que-no-resuelve-un-smbolo-personalizado&quot;&gt;Lo que no resuelve un símbolo personalizado&lt;/h2&gt;

  &lt;p&gt;Un SF Symbol no es una ilustración. Es un icono pequeño, reconocible y ópticamente alineado con el resto del sistema. Si metes un logo complejo con gradientes, sombras y detalles finos, va a sufrir en tamaños pequeños y en modo oscuro.&lt;/p&gt;

  &lt;p&gt;Tampoco conviene copiar símbolos de Apple que representan productos o features y modificar sus trazos. La app SF Symbols marca algunos símbolos como no personalizables.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; Las anotaciones dependen de que el número y el orden de los paths se mantengan. Si editas el SVG y eliminas o reordenas paths, las anotaciones pueden quedar desincronizadas. Valida y revisa el símbolo después de cada cambio.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;accesibilidad-y-movimiento&quot;&gt;Accesibilidad y movimiento&lt;/h2&gt;

  &lt;p&gt;Un icono animado sigue siendo un icono. Si transmite información, necesita una etiqueta accesible:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sparkles&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;accessibilityLabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Highlight&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Si es decorativo, ocúltalo:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sparkles&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;accessibilityHidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Y no todo el mundo quiere movimiento. Respeta &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;accessibilityReduceMotion&lt;/code&gt; y evita animaciones indefinidas cuando la persona ha pedido reducir el movimiento:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;@Environment&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(\&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accessibilityReduceMotion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;reduceMotion&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sparkles&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;symbolEffect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pulse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;isActive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;isPulsing&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reduceMotion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Para tamaños, usa estilos de texto (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.font(.title)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.font(.largeTitle)&lt;/code&gt;) en lugar de píxeles fijos. Así el símbolo acompaña a Dynamic Type.&lt;/p&gt;

  &lt;h2 id=&quot;checklist-antes-de-darlo-por-terminado&quot;&gt;Checklist antes de darlo por terminado&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;¿Está en un &lt;strong&gt;Symbol Image Set&lt;/strong&gt; del asset catalog?&lt;/li&gt;
    &lt;li&gt;¿Tiene capas suficientes para los modos que vas a usar?&lt;/li&gt;
    &lt;li&gt;¿Has probado monochrome, hierarchical, palette y multicolor?&lt;/li&gt;
    &lt;li&gt;¿Has probado los efectos con todas las escalas y pesos?&lt;/li&gt;
    &lt;li&gt;¿Se ve bien en modo claro, oscuro y con poco contraste?&lt;/li&gt;
    &lt;li&gt;¿Tiene etiqueta de accesibilidad o está oculto si es decorativo?&lt;/li&gt;
    &lt;li&gt;¿Respeta Reduce Motion?&lt;/li&gt;
    &lt;li&gt;¿Has validado el SVG en la app SF Symbols?&lt;/li&gt;
  &lt;/ul&gt;

  &lt;h2 id=&quot;conclusin&quot;&gt;Conclusión&lt;/h2&gt;

  &lt;p&gt;Los SF Symbols personalizados son una de esas funciones que parecen un detalle de diseño y terminan siendo una decisión de arquitectura visual. Si los tratas como SVG estáticos, tienes iconos bonitos. Si los tratas como símbolos anotados, tienes iconos que se colorean, se animan y se comportan como los de Apple.&lt;/p&gt;

  &lt;p&gt;La próxima vez que necesites un icono que no está en el catálogo, no empieces por un PNG. Empieza por una plantilla de SF Symbols. El resultado encaja mejor, escala mejor y se mueve igual de bien.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/technologyoverviews/custom-sf-symbols&quot;&gt;Creating custom symbols&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/technologyoverviews/annotating-sf-symbols&quot;&gt;Annotating custom symbols&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/sf-symbols&quot;&gt;SF Symbols&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/design/human-interface-guidelines/sf-symbols&quot;&gt;Human Interface Guidelines: SF Symbols&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/symbols&quot;&gt;Symbols framework&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2023/10257/&quot;&gt;WWDC23: Create animated symbols&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2023/10258/&quot;&gt;WWDC23: Animate symbols in your app&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2025/337/&quot;&gt;WWDC25: What’s new in SF Symbols 7&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">SwiftUI: quitar Liquid Glass de un toolbar (sin renunciar al sistema)</title>
    <link href="https://www.obocat.com/blog/2026/11/04/swiftui-toolbar-sin-liquid-glass/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/11/04/swiftui-toolbar-sin-liquid-glass/</id>
    <published>2026-11-04T00:00:00+00:00</published>
    <updated>2026-11-04T00:00:00+00:00</updated>
    <summary type="text">Cómo usar sharedBackgroundVisibility(.hidden) para mantener un grupo de la barra de navegación sin Liquid Glass, y por qué UIDesignRequiresCompatibility ya no sirve.</summary>
    
    <category term="iOS"/>
    
    <category term="SwiftUI"/>
    
    <category term="Liquid Glass"/>
    
    <category term="Toolbar"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/11/04/swiftui-toolbar-sin-liquid-glass/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;Liquid Glass es el lenguaje visual que Apple introdujo en iOS 26. Cambia la forma en que se agrupan y se dibujan las barras de navegación, los botones y las sheets: los elementos del toolbar comparten un fondo de Liquid Glass que se adapta al contenido que hay detrás. En la mayoría de los casos, adoptarlo es lo correcto.&lt;/p&gt;

  &lt;p&gt;Pero hay excepciones. A veces, por diseño de producto o por identidad de marca, nos piden mantener un componente concreto sin ese fondo: un logo que ya tiene su propia forma, un avatar que necesita un color sólido o un control que debe integrarse en una superficie propia. No hace falta renunciar al sistema entero para conseguirlo. SwiftUI tiene una API pensada precisamente para esta excepción.&lt;/p&gt;

  &lt;p&gt;Si estás preparando la app para compilar con el SDK de iOS 27 y para los nuevos dispositivos como el iPhone Duo, el primer paso es resolver la adaptación de layout y cámara; lo conté en &lt;a href=&quot;/blog/2026/10/29/iphone-duo-layout-camara/&quot;&gt;Adaptar una app al iPhone Duo: layouts fáciles, cámara difícil&lt;/a&gt;. Una vez resuelta esa base, tiene más sentido afinar excepciones como la de este artículo.&lt;/p&gt;

  &lt;h2 id=&quot;la-api-sharedbackgroundvisibilityhidden&quot;&gt;La API: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sharedBackgroundVisibility(.hidden)&lt;/code&gt;&lt;/h2&gt;

  &lt;p&gt;El modificador se aplica al contenido del toolbar, no a la vista que hay dentro. Este es el ejemplo mínimo:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SwiftUI&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ToolbarWithoutGlassView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;NavigationStack&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Test&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toolbar&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;kt&quot;&gt;ToolbarItemGroup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;placement&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;topBarLeading&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;kt&quot;&gt;Button&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Test&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Tapped&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sharedBackgroundVisibility&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; El modificador va después del cierre de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ToolbarItemGroup&lt;/code&gt;, no dentro del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Button&lt;/code&gt;. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sharedBackgroundVisibility&lt;/code&gt; es una API de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ToolbarContent&lt;/code&gt;; si la aplicas a una &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;View&lt;/code&gt;, el compilador no la encontrará.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;El ejemplo da por hecho un target de iOS 26 o superior; si tu app soporta versiones anteriores, usa la extensión de compatibilidad que veremos más adelante.&lt;/p&gt;

  &lt;h2 id=&quot;qu-hace-exactamente&quot;&gt;Qué hace exactamente&lt;/h2&gt;

  &lt;p&gt;Antes de usarlo, merece la pena entender qué cambia y qué no. El nombre describe el comportamiento: controla la visibilidad del fondo que comparten los elementos del toolbar. Al pasarle &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.hidden&lt;/code&gt;, el sistema deja de dibujar ese fondo compartido y coloca el elemento en su propio grupo. No es un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;background(.clear)&lt;/code&gt; ni un juego de transparencias: es una instrucción al sistema para que no aplique el efecto de Liquid Glass a ese contenido.&lt;/p&gt;

  &lt;p&gt;Con un solo elemento, el resultado es ese elemento sin la cápsula compartida; con varios, el grupo entero deja de usar el fondo común. Los botones siguen siendo interactivos: lo que cambia es el tratamiento visual del contenedor, no su comportamiento. El resto de elementos del toolbar conserva el suyo.&lt;/p&gt;

  &lt;h2 id=&quot;un-caso-real-una-marca-que-ya-tiene-su-propia-identidad&quot;&gt;Un caso real: una marca que ya tiene su propia identidad&lt;/h2&gt;

  &lt;p&gt;Veamos un caso típico. Imagina el logo de una marca en la esquina superior izquierda. Si lo metes en una cápsula de Liquid Glass, el sistema añade una capa que compite con el logo y puede hacer que parezca un botón genérico. Ocultar el fondo compartido permite que el logo se lea como contenido de la barra.&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SwiftUI&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BrandToolbarView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;NavigationStack&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Home&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toolbar&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;kt&quot;&gt;ToolbarItemGroup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;placement&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;topBarLeading&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;kt&quot;&gt;Button&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Brand tapped&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                            &lt;span class=&quot;kt&quot;&gt;HStack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;spacing&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                                &lt;span class=&quot;kt&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;systemName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sparkles&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;foregroundStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

                                &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Acme&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;font&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;headline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                        &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;accessibilityLabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Acme&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sharedBackgroundVisibility&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Si el logo no es interactivo, no lo escribas como un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Button&lt;/code&gt; solo para que parezca parte del toolbar. Un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;HStack&lt;/code&gt; normal, con una etiqueta de accesibilidad adecuada, suele ser más coherente. Si lo es, mantén el área táctil y el foco de teclado que tendría cualquier otro botón.&lt;/p&gt;

  &lt;h2 id=&quot;qu-se-pierde-al-quitar-el-fondo-de-liquid-glass&quot;&gt;Qué se pierde al quitar el fondo de Liquid Glass&lt;/h2&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; Quitar Liquid Glass no es solo decoración. El fondo separa el contenido del toolbar de lo que hay detrás y ayuda a mantener la legibilidad cuando la pantalla tiene fotos, mapas o colores vivos. Al ocultarlo, esa responsabilidad recae en tu diseño.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Antes de dar por buena una excepción, comprueba:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;El contraste en modo claro y oscuro.&lt;/li&gt;
    &lt;li&gt;El contenido que queda detrás del elemento, especialmente al hacer scroll.&lt;/li&gt;
    &lt;li&gt;Los ajustes Reducir transparencia y Aumentar contraste.&lt;/li&gt;
    &lt;li&gt;El tamaño de texto dinámico (Dynamic Type): el texto no debería romper el grupo.&lt;/li&gt;
    &lt;li&gt;El área táctil, que debe seguir siendo cómoda.&lt;/li&gt;
    &lt;li&gt;VoiceOver: si el elemento es un botón, necesita una etiqueta clara; si es una marca, no debería anunciarse como una acción.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;Ocultar el fondo es fácil. Lo difícil es que el resultado siga siendo claro, accesible y coherente con el resto de la pantalla.&lt;/p&gt;

  &lt;h2 id=&quot;compatibilidad-con-versiones-anteriores&quot;&gt;Compatibilidad con versiones anteriores&lt;/h2&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sharedBackgroundVisibility&lt;/code&gt; está disponible a partir de iOS 26.0, y también en iPadOS 26 y macOS 26. El ejemplo usa posiciones de la barra de navegación en iOS. Si tu app da soporte a versiones anteriores, necesitas compilar con el SDK de iOS 26 o posterior y proteger la ejecución con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;#available&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;Una extensión reutilizable evita duplicar el contenido del toolbar:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SwiftUI&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ToolbarContent&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@ToolbarContentBuilder&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;hideSharedGlassIfAvailable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ToolbarContent&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;#available(iOS 26.0, *)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;sharedBackgroundVisibility&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CompatibleToolbarView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;some&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;View&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;NavigationStack&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Test&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toolbar&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;kt&quot;&gt;ToolbarItemGroup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;placement&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;topBarLeading&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;kt&quot;&gt;Button&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Test&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Tapped&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hideSharedGlassIfAvailable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;cp&quot;&gt;#Preview {&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;CompatibleToolbarView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;La extensión aprovecha &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ToolbarContentBuilder&lt;/code&gt; para devolver el mismo contenido con o sin el modificador. En iOS 26 y posteriores oculta el fondo; en versiones anteriores devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self&lt;/code&gt; y no cambia nada.&lt;/p&gt;

  &lt;h2 id=&quot;uidesignrequirescompatibility-el-final-de-la-prrroga&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIDesignRequiresCompatibility&lt;/code&gt;: el final de la prórroga&lt;/h2&gt;

  &lt;p&gt;Todo esto nos lleva a la pregunta que suele aparecer después: ¿y la clave global? Durante la transición a iOS 26, Apple ofreció una vía de escape: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIDesignRequiresCompatibility&lt;/code&gt; en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Info.plist&lt;/code&gt;.&lt;/p&gt;

  &lt;div class=&quot;language-xml highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nt&quot;&gt;&amp;lt;key&amp;gt;&lt;/span&gt;UIDesignRequiresCompatibility&lt;span class=&quot;nt&quot;&gt;&amp;lt;/key&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;true/&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YES&lt;/code&gt;, la app se ejecuta en modo de compatibilidad y conserva el aspecto anterior. Fue útil para ganar tiempo, pero nunca fue una estrategia de diseño: es una prórroga para adaptar la app, no una forma de mantener dos lenguajes visuales indefinidamente.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; Según la documentación de Apple, el sistema ignora esta clave cuando compilas con el SDK de iOS 27 o posterior. Si tu app se compila con el SDK de iOS 27, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIDesignRequiresCompatibility&lt;/code&gt; ya no te devuelve el diseño anterior.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Hay un matiz que no conviene pasar por alto: si sigues compilando con el SDK de iOS 26, la clave puede tener efecto en iOS 26. Pero eso significa quedarse en un SDK antiguo, con las consecuencias de mantenimiento y compatibilidad que eso implica. No es una solución a largo plazo.&lt;/p&gt;

  &lt;p&gt;Y hay una fecha que convierte ese matiz en algo más urgente. &lt;a href=&quot;https://developer.apple.com/news/?id=k1mtkt1k&quot;&gt;Apple ha anunciado&lt;/a&gt; que, a partir de abril de 2027, las apps de iOS y iPadOS que se suban a App Store Connect deberán compilarse con el SDK de iOS 27 o posterior. No es una fecha en la que iOS deje de leer la clave en apps ya instaladas, sino una fecha de caducidad práctica: en cuanto actualices el SDK para publicar, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIDesignRequiresCompatibility&lt;/code&gt; dejará de tener efecto. Las builds ya publicadas no cambian por sí solas, pero las actualizaciones tendrán que asumir el nuevo diseño.&lt;/p&gt;

  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Necesidad&lt;/th&gt;
        &lt;th&gt;Herramienta&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td&gt;Ocultar Liquid Glass de un elemento o grupo del toolbar&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.sharedBackgroundVisibility(.hidden)&lt;/code&gt; en iOS 26+&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Separar grupos manteniendo Liquid Glass&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ToolbarSpacer&lt;/code&gt; en iOS 26+&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;Modo de compatibilidad para toda la app&lt;/td&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIDesignRequiresCompatibility&lt;/code&gt; (ignorado con el SDK de iOS 27)&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;

  &lt;h2 id=&quot;mi-opinin-excepciones-no-una-norma&quot;&gt;Mi opinión: excepciones, no una norma&lt;/h2&gt;

  &lt;p&gt;Con todo esto sobre la mesa, mi postura es clara: la consistencia con el sistema debería ser la opción por defecto. Los usuarios aprenden una vez cómo se ven y se comportan los controles de iOS, y Liquid Glass forma parte de ese lenguaje visual. Cambiarlo en un componente aislado puede hacer que el usuario dude si eso es un botón, un elemento decorativo o contenido.&lt;/p&gt;

  &lt;p&gt;Pero la consistencia no es una regla absoluta. Hay excepciones legítimas: una marca que ya tiene su propio lenguaje, un control que necesita un fondo propio para ser legible o una superficie que no debe competir con el Liquid Glass del sistema. Lo importante es que sea una excepción deliberada, documentada y probada, no una forma de evitar adaptar la app.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/toolbarcontent/sharedbackgroundvisibility%28_%3A%29&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sharedBackgroundVisibility(_:)&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/bundleresources/information-property-list/uidesignrequirescompatibility&quot;&gt;UIDesignRequiresCompatibility&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/toolbaritemplacement/topbarleading&quot;&gt;ToolbarItemPlacement.topBarLeading&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/wwdc2025/323/&quot;&gt;Build a SwiftUI app with the new design (WWDC25)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://sarunw.com/posts/swiftui-toolbar-item-grouping-ios-26/&quot;&gt;When toolbar items share a glass background in iOS 26&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">ArrangementView: composición y distribución del espacio en SwiftUI</title>
    <link href="https://www.obocat.com/blog/2026/10/31/arrangementview-composicion-espacio-swiftui/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/10/31/arrangementview-composicion-espacio-swiftui/</id>
    <published>2026-10-31T00:00:00+00:00</published>
    <updated>2026-10-31T00:00:00+00:00</updated>
    <summary type="text">Cómo ArrangementView lleva la gestión del espacio en SwiftUI de la prioridad entre vistas a la composición entre secciones.</summary>
    
    <category term="iOS"/>
    
    <category term="iPhone Duo"/>
    
    <category term="SwiftUI"/>
    
    <category term="Layout"/>
    
    <category term="ArrangementView"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/10/31/arrangementview-composicion-espacio-swiftui/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;En el &lt;a href=&quot;/blog/2026/10/29/iphone-duo-layout-camara/&quot;&gt;artículo anterior&lt;/a&gt; vimos cómo adaptamos una app al iPhone Duo: los layouts fueron mucho más sencillos de lo esperado y la cámara fue la parte difícil. Una de las piezas que hizo que el layout fuera tan llevadero fue &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;Pero antes de entrar en la API, conviene entender qué problema resuelve. Y para eso hay que empezar por algo más conocido: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt;.&lt;/p&gt;

  &lt;h2 id=&quot;de-la-prioridad-de-layout-a-la-composicin&quot;&gt;De la prioridad de layout a la composición&lt;/h2&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt; permite influir en cómo un contenedor reparte el espacio entre sus vistas hijas. Cuando el espacio es limitado, SwiftUI puede usar esa prioridad para decidir qué vista conserva su tamaño ideal y cuál se comprime.&lt;/p&gt;

  &lt;p&gt;Por ejemplo:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;HStack&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Media&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layoutPriority&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;kt&quot;&gt;Text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Products&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;La primera vista tiene preferencia frente a la segunda cuando hay que negociar el espacio. Es una herramienta local: actúa entre vistas hermanas dentro de un mismo contenedor.&lt;/p&gt;

  &lt;p&gt;El problema aparece cuando la decisión ya no es “qué &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Text&lt;/code&gt; se encoge antes”, sino “cómo se relacionan dos secciones completas de la interfaz”. Ahí &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt; se queda corto: no expresa una política de composición.&lt;/p&gt;

  &lt;h2 id=&quot;composition-level-layout&quot;&gt;Composition-level layout&lt;/h2&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; sube un nivel de abstracción. En lugar de repartir espacio entre vistas individuales, permite declarar una relación entre una sección primaria y una secundaria, y dejar que el contenedor decida cómo componerlas según el espacio disponible y la pose del dispositivo.&lt;/p&gt;

  &lt;p&gt;En el iPhone Duo esto encaja especialmente bien: la geometría cambia entre pantallas y poses, pero la relación principal/secundaria puede mantenerse aunque cambie la disposición.&lt;/p&gt;

  &lt;p&gt;Un ejemplo:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;ArrangementView&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mediaSection&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;splitArrangementFixedLayoutSize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;horizontal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;vertical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;secondary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;productsSection&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;splitArrangementFixedLayoutSize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;horizontal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;vertical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arrangementViewStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Aquí hay tres decisiones distintas:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; establece la relación entre &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mediaSection&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;productsSection&lt;/code&gt;.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.arrangementViewStyle(.split)&lt;/code&gt; elige la estrategia de composición: las dos secciones se reparten el espacio en una disposición dividida.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;splitArrangementFixedLayoutSize(horizontal:vertical:)&lt;/code&gt; indica en qué ejes cada sección debe usar su tamaño ideal en lugar de estirarse.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;En el ejemplo, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mediaSection&lt;/code&gt; no fija ninguno de los dos ejes, mientras que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;productsSection&lt;/code&gt; fija la dimensión vertical. El resultado no es un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;frame&lt;/code&gt; rígido: es una restricción de tamaño que el contenedor interpreta según el espacio y la pose. Si no hay sitio para mantener la split, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; puede mostrar solo la vista primaria.&lt;/p&gt;

  &lt;h2 id=&quot;qu-hace-cada-pieza&quot;&gt;Qué hace cada pieza&lt;/h2&gt;

  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;API&lt;/th&gt;
        &lt;th&gt;Responsabilidad&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt;&lt;/td&gt;
        &lt;td&gt;Influye en la negociación del espacio entre vistas.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt;&lt;/td&gt;
        &lt;td&gt;Define cómo se componen y distribuyen las secciones primaria y secundaria.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;splitArrangementFixedLayoutSize&lt;/code&gt;&lt;/td&gt;
        &lt;td&gt;Expresa restricciones de tamaño por eje para una sección.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;arrangementViewStyle(.split)&lt;/code&gt;&lt;/td&gt;
        &lt;td&gt;Establece la estrategia visual de composición.&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;

  &lt;p&gt;La diferencia importante es de nivel. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt; responde a una pregunta local: “¿qué vista debería conservar su tamaño preferido?”. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; responde a una pregunta estructural: “¿qué relación hay entre estas dos secciones y cómo debe cambiar cuando el contenedor cambia de forma?”.&lt;/p&gt;

  &lt;h2 id=&quot;el-matiz-de-split&quot;&gt;El matiz de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.split&lt;/code&gt;&lt;/h2&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.split&lt;/code&gt; no significa “siempre lado a lado”. Significa que el contenedor intentará repartir el espacio entre las dos secciones y decidirá la orientación según el espacio disponible.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;En el iPhone Duo también tiene en cuenta regiones reservadas como el pliegue.&lt;/p&gt;

  &lt;p&gt;Si quieres limitar la split a un eje concreto, puedes usar:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arrangementViewStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;horizontal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Eso es útil cuando el diseño solo tiene sentido en horizontal. Pero conviene no forzarlo sin necesidad: parte del valor de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; es precisamente adaptar la composición a la pose del dispositivo.&lt;/p&gt;

  &lt;h2 id=&quot;cundo-usarlo-y-cundo-no&quot;&gt;Cuándo usarlo y cuándo no&lt;/h2&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; no es un sustituto general de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;HStack&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VStack&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ZStack&lt;/code&gt;. Es un contenedor especializado para una relación estable entre contenido principal y secundario.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Antes de usarlo, merece la pena responder:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;¿La relación principal/secundaria tiene sentido en todas las poses?&lt;/li&gt;
    &lt;li&gt;¿Qué sección puede desaparecer cuando no hay espacio?&lt;/li&gt;
    &lt;li&gt;¿La vista secundaria sigue siendo accesible si el contenedor la oculta?&lt;/li&gt;
    &lt;li&gt;¿El cambio entre split y overlay requiere intercambiar los roles de primary y secondary?&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;Ese último punto es fácil de pasar por alto. En una split, la vista primaria es la que permanece cuando no cabe la división. En un overlay, la primaria es la que queda por encima. La misma palabra no siempre implica la misma jerarquía visual. Si el diseño alterna entre estilos, conviene revisar los roles.&lt;/p&gt;

  &lt;p&gt;También hay que recordar que estas configuraciones expresan preferencias, no resultados garantizados. El contenedor decide al final. Si la interfaz necesita saber exactamente qué disposición se está mostrando, puede que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; no sea la herramienta adecuada.&lt;/p&gt;

  &lt;h2 id=&quot;conclusin&quot;&gt;Conclusión&lt;/h2&gt;

  &lt;p&gt;Podemos entender &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; como una evolución conceptual de la gestión tradicional del espacio en SwiftUI, pero aplicada a un nivel superior.&lt;/p&gt;

  &lt;p&gt;Mientras &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt; interviene en la negociación del espacio entre vistas individuales, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; permite definir políticas de composición entre bloques completos de contenido.&lt;/p&gt;

  &lt;p&gt;En otras palabras: pasamos de decidir qué vista tiene prioridad durante el layout a definir cómo queremos que se componga y distribuya una interfaz.&lt;/p&gt;

  &lt;p&gt;Una forma de resumir la diferencia:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layoutPriority&lt;/code&gt;: layout negotiation priority.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt;: compositional layout policy.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;Esa distinción ayuda a pensar la interfaz desde una perspectiva más estructural, separando las decisiones de composición de los detalles internos del layout de cada sección.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/arrangementview&quot;&gt;ArrangementView&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/view/splitarrangementfixedlayoutsize%28horizontal%3Avertical%3A%29&quot;&gt;splitArrangementFixedLayoutSize(horizontal:vertical:)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/swiftui/view/arrangementviewstyle%28%5F%3A%29&quot;&gt;arrangementViewStyle(_:)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://fatbobman.com/en/posts/arrangementview-think-before-you-arrange&quot;&gt;ArrangementView: Think Before You Arrange&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;/blog/2026/10/29/iphone-duo-layout-camara/&quot;&gt;Adaptar una app al iPhone Duo&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">Adaptar una app al iPhone Duo: layouts fáciles, cámara difícil</title>
    <link href="https://www.obocat.com/blog/2026/10/29/iphone-duo-layout-camara/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/10/29/iphone-duo-layout-camara/</id>
    <published>2026-10-29T00:00:00+00:00</published>
    <updated>2026-10-29T00:00:00+00:00</updated>
    <summary type="text">Cómo adaptamos una app al iPhone Duo con ArrangementView y AVCaptureDevice.RotationCoordinator.</summary>
    
    <category term="iOS"/>
    
    <category term="iPhone Duo"/>
    
    <category term="AVFoundation"/>
    
    <category term="SwiftUI"/>
    
    <category term="Camera"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/10/29/iphone-duo-layout-camara/">&lt;div class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;

  &lt;p&gt;Cuando Apple presentó el iPhone Duo, la primera pregunta fue cuánto trabajo nos costaría adaptar la app. La respuesta corta: los layouts, mucho menos de lo esperado; la cámara, bastante más. No porque la API fuera especialmente complicada, sino porque el problema solo aparece cuando el dispositivo cambia de forma delante de ti.&lt;/p&gt;

  &lt;h2 id=&quot;un-iphone-que-no-es-solo-un-iphone-ms-grande&quot;&gt;Un iPhone que no es solo un iPhone más grande&lt;/h2&gt;

  &lt;p&gt;El Duo tiene dos pantallas, una exterior y otra interior, y puede estar cerrado, abierto o parcialmente plegado. Al abrirlo, la app puede pasar de una pantalla a la otra, la geometría cambia y los controles del sistema pueden reorganizarse. Además, la cámara que está mirando hacia el usuario puede cambiar de dirección.&lt;/p&gt;

  &lt;p&gt;Eso rompe una suposición muy cómoda que arrastrábamos de iOS: que la orientación de la interfaz y la orientación de la cámara eran dos cosas más o menos equivalentes. En un plegable, la app puede cambiar de pantalla sin que haya una rotación clásica, y la cámara puede seguir apuntando hacia otro sitio.&lt;/p&gt;

  &lt;h2 id=&quot;los-layouts-arrangementview-hizo-casi-todo-el-trabajo&quot;&gt;Los layouts: ArrangementView hizo casi todo el trabajo&lt;/h2&gt;

  &lt;p&gt;Para la estructura principal usamos &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt;, el contenedor que Apple añadió para organizar una vista primaria y una secundaria según la pose del dispositivo. En UIKit existe el equivalente &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIArrangementViewController&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;La idea es sencilla:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;ArrangementView&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;LibraryView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;secondary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;DetailView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arrangementViewStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;axes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;horizontal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;El estilo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;split&lt;/code&gt; coloca las dos vistas lado a lado cuando el contenedor es más ancho que alto, y las apila cuando es más alto que ancho. Además, tiene en cuenta regiones reservadas como el pliegue. El estilo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;overlay&lt;/code&gt; funciona de forma parecida a un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ZStack&lt;/code&gt;: cuando el dispositivo está cerrado o completamente abierto coloca la vista primaria sobre la secundaria, y cuando está parcialmente plegado las separa alrededor del pliegue.&lt;/p&gt;

  &lt;p&gt;En nuestro caso, la primera aproximación fue bastante trivial. Pasamos de una pantalla única a una jerarquía primaria/secundaria y el sistema resolvió la mayor parte de los cambios de tamaño y de posición. Lo que quedó fue ajustar detalles: qué vista tenía prioridad en cada pose, dónde colocar los controles y cómo evitar que algo importante cayera justo en el pliegue o debajo de la cámara interior.&lt;/p&gt;

  &lt;p&gt;Para eso último no conviene inventarse el cálculo del pliegue. Apple expone las regiones reservadas:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;GeometryReader&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proxy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;divisions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proxy&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reservedRegions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;kind&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;division&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;occlusions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proxy&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reservedRegions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;kind&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;occlusion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// Ajustar el contenido según las regiones activas.&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;La recomendación es usar el tamaño real de la escena o del contenedor, no dimensiones fijas de iPhone, y no tomar decisiones de layout a partir de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIInterfaceOrientation&lt;/code&gt;. En un Duo, la orientación clásica no cuenta toda la historia.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; No coloques un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; dentro de un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NavigationSplitView&lt;/code&gt;, una lista, un scroll view o cualquier contenedor que pueda dejar parte de la vista inaccesible.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2 id=&quot;la-cmara-el-problema-que-no-se-vea-en-el-simulador&quot;&gt;La cámara: el problema que no se veía en el simulador&lt;/h2&gt;

  &lt;p&gt;El layout se podía validar bastante bien en el simulador. La cámara, no.&lt;/p&gt;

  &lt;p&gt;El síntoma aparecía al abrir el dispositivo: la preview cambiaba de orientación y no siempre quedaba nivelada. El contenido se redimensionaba, la capa de preview pasaba a otra pantalla y la rotación dejaba de ser la esperada. En el simulador el layout se veía correcto; el problema real necesitaba un Duo en la mano.&lt;/p&gt;

  &lt;p&gt;La causa de fondo es que el sensor de una cámara tiene una orientación física fija. La rotación del dispositivo no cambia el sensor, y el pipeline de captura no compensa esa diferencia por su cuenta. En un iPhone normal suele bastar con observar la orientación de la interfaz, pero en un plegable hay cambios de pantalla y de pose que no encajan en ese modelo.&lt;/p&gt;

  &lt;p&gt;La solución no fue calcular ángulos a mano. Fue usar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AVCaptureDevice.RotationCoordinator&lt;/code&gt; como única fuente de verdad.&lt;/p&gt;

  &lt;h2 id=&quot;rotationcoordinator-ngulos-relativos-al-horizonte&quot;&gt;RotationCoordinator: ángulos relativos al horizonte&lt;/h2&gt;

  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AVCaptureDevice.RotationCoordinator&lt;/code&gt; monitoriza la orientación física de un dispositivo de captura y proporciona ángulos de ajuste para mantener las imágenes niveladas con respecto a la gravedad.&lt;/p&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--note&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Nota:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AVCaptureDevice.RotationCoordinator&lt;/code&gt; existe desde iOS 17, así que no es exclusiva del Duo; lo que cambia es que aquí pasa a ser la pieza central.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;El coordinador publica dos ángulos:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;videoRotationAngleForHorizonLevelPreview&lt;/code&gt;: para la capa de preview.&lt;/li&gt;
    &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;videoRotationAngleForHorizonLevelCapture&lt;/code&gt;: para las fotos y los vídeos capturados.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;El de preview tiene en cuenta además la posición de la capa dentro de la jerarquía de vistas. Por eso puede ser distinto del de captura. En el Duo, ambos se actualizan cuando la app cambia de pantalla.&lt;/p&gt;

  &lt;p&gt;El coordinador se crea con el dispositivo y la capa de preview:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;coordinator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureDevice&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;RotationCoordinator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;nv&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;nv&quot;&gt;previewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;previewLayer&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Hay tres detalles que fueron clave para que funcionara de verdad:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;&lt;strong&gt;La capa tiene que estar en una ventana.&lt;/strong&gt; El coordinador mide su posición en la jerarquía. Si se crea con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;previewLayer: nil&lt;/code&gt;, nunca dará un ángulo de preview, aunque la capa aparezca después.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Hay que recrear el coordinador cuando cambia la cámara o la capa.&lt;/strong&gt; Un coordinador está ligado a un dispositivo durante toda su vida. Si pasamos de la cámara interior a la exterior, o la capa se mueve a otra ventana, hay que crear uno nuevo.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Hay que leer los valores iniciales y luego observar los cambios.&lt;/strong&gt; Si solo observas, la preview puede quedarse torcida hasta la primera rotación.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;Un observador mínimo podría quedar así:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;@MainActor&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CameraRotationObserver&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;coordinator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureDevice&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;RotationCoordinator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;observations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSKeyValueObservation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]()&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureDevice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;weak&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;previewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureVideoPreviewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;setDevice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureDevice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;restart&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;setPreviewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureVideoPreviewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;previewLayer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;restart&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;restart&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;device&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;observations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;forEach&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;$0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;invalidate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;observations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;removeAll&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;coordinator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AVCaptureDevice&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;RotationCoordinator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;previewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;previewLayer&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt;

        &lt;span class=&quot;nf&quot;&gt;applyPreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngleForHorizonLevelPreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;applyCapture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngleForHorizonLevelCapture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;observations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;observe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;\&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngleForHorizonLevelPreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;nv&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;weak&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;change&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;angle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;change&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                &lt;span class=&quot;kt&quot;&gt;MainActor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;assumeIsolated&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;applyPreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;observations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;observe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;\&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngleForHorizonLevelCapture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;nv&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;weak&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;change&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;angle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;change&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
                &lt;span class=&quot;kt&quot;&gt;MainActor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;assumeIsolated&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;applyCapture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;applyPreview&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;angle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CGFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;previewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;connection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;applyCapture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;angle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CGFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Enviar el ángulo al actor que posee la sesión de captura.&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Aplicar el ángulo de preview es una sola línea:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;previewLayer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;connection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Para la captura, el ángulo se aplica a la conexión de vídeo de cada output:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;connection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;with&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;video&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)?&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;videoRotationAngle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;h2 id=&quot;el-detalle-de-la-capa-de-preview&quot;&gt;El detalle de la capa de preview&lt;/h2&gt;

  &lt;p&gt;En SwiftUI, la capa de preview suele vivir dentro de un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UIViewRepresentable&lt;/code&gt;. Esa vista se construye antes de que el sistema la instale en una ventana. Por eso conviene avisar al observador cuando la capa se mueve a una ventana:&lt;/p&gt;

  &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;PreviewView&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIView&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;previewLayerDidMoveToWindow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;AVCaptureVideoPreviewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Void&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)?&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didMoveToWindow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;didMoveToWindow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;guard&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;previewLayerDidMoveToWindow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;previewLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;

  &lt;p&gt;Ese callback es el que recrea el coordinador con la capa ya instalada. En un Duo, además, la app puede moverse entre pantallas, así que este tipo de transición no es un caso raro: es parte del funcionamiento normal.&lt;/p&gt;

  &lt;h2 id=&quot;lo-que-el-simulador-no-te-cuenta&quot;&gt;Lo que el simulador no te cuenta&lt;/h2&gt;

  &lt;blockquote class=&quot;doc-callout doc-callout--important&quot;&gt;
    &lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; El simulador sirve para validar layouts, tamaños, barras y poses, pero la cámara hay que probarla en un dispositivo físico.&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Nuestra lista de pruebas fue algo así:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Cerrar, abrir y dejar el Duo parcialmente plegado con la cámara activa.&lt;/li&gt;
    &lt;li&gt;Rotar en cada pose: vertical, horizontal, tipo tienda de campaña y tipo portátil.&lt;/li&gt;
    &lt;li&gt;Cambiar entre cámara interior, exterior y trasera.&lt;/li&gt;
    &lt;li&gt;Verificar que la preview no salta al pasar de una pantalla a otra.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;El problema era difícil precisamente por esto: no era un bug de lógica pura, era un bug de estado físico. La misma configuración podía fallar solo en una pose concreta y solo durante una fracción de segundo.&lt;/p&gt;

  &lt;h2 id=&quot;conclusin&quot;&gt;Conclusión&lt;/h2&gt;

  &lt;p&gt;Adaptar los layouts al iPhone Duo fue mucho más sencillo de lo que esperaba. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ArrangementView&lt;/code&gt; y las regiones reservadas resolvieron la mayor parte del trabajo, y la primera aproximación funcionó casi sola.&lt;/p&gt;

  &lt;p&gt;La cámara fue otra historia. La clave fue dejar de pensar en términos de orientación de interfaz y usar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AVCaptureDevice.RotationCoordinator&lt;/code&gt; como fuente de verdad, recreándolo cuando cambia el dispositivo o la capa de preview. Ahí se acabó el baile de ángulos al abrir el dispositivo.&lt;/p&gt;

  &lt;p&gt;Si estás adaptando una app al Duo, empezaría por el layout y dedicaría tiempo aparte a la cámara. Y, sobre todo, probaría en un dispositivo físico: hay cosas que el simulador simplemente no te puede contar.&lt;/p&gt;

  &lt;h2 id=&quot;referencias&quot;&gt;Referencias&lt;/h2&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/technologyoverviews/preparing-your-app-for-iphone-duo&quot;&gt;Preparing your app for iPhone Duo&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/videos/play/tech-talks/111465/&quot;&gt;Build a great camera experience for iPhone Duo&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/avkit/choosing-a-camera-by-the-direction-it-faces&quot;&gt;Choosing a camera by the direction it faces&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/avfoundation/supporting-device-rotation-in-your-camera-app&quot;&gt;Supporting device rotation in your camera app&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/documentation/avfoundation/avcapturedevice/rotationcoordinator&quot;&gt;AVCaptureDevice.RotationCoordinator&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;

&lt;/div&gt;

</content>
  </entry>
  
    
    
    
  <entry xml:lang="es">
    <title type="text">Hola mundo</title>
    <link href="https://www.obocat.com/blog/2026/10/23/hola-mundo/" rel="alternate" type="text/html" hreflang="es"/>
    <id>https://www.obocat.com/blog/2026/10/23/hola-mundo/</id>
    <published>2026-10-23T00:00:00+00:00</published>
    <updated>2026-10-23T00:00:00+00:00</updated>
    <summary type="text">Primer artículo del blog: notas sobre desarrollo iOS, arquitectura y producto.</summary>
    
    <category term="iOS"/>
    
    <category term="Swift"/>
    
    <content type="html" xml:base="https://www.obocat.com/blog/2026/10/23/hola-mundo/">&lt;p class=&quot;lang-es&quot; lang=&quot;es&quot;&gt;Hola mundo. Este es el primer artículo del blog. Aquí iré compartiendo notas sobre desarrollo iOS, arquitectura y producto.&lt;/p&gt;

</content>
  </entry>
  
</feed>
