<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.4.3">Jekyll</generator><link href="http://equinocios.com/feed.xml" rel="self" type="application/atom+xml" /><link href="http://equinocios.com/" rel="alternate" type="text/html" /><updated>2017-06-09T22:00:11+00:00</updated><id>http://equinocios.com/</id><title type="html">equinociOS</title><subtitle>20 artigos de voluntários durante o mês de Março para comemorar o equinociOS</subtitle><entry><title type="html">Persistência de dados usando Core Data</title><link href="http://equinocios.com/banco%20de%20dados/2017/03/30/persistencia-de-dados-usando-core-data/" rel="alternate" type="text/html" title="Persistência de dados usando Core Data" /><published>2017-03-30T12:00:00+00:00</published><updated>2017-03-30T12:00:00+00:00</updated><id>http://equinocios.com/banco%20de%20dados/2017/03/30/persistencia-de-dados-usando-core-data</id><content type="html" xml:base="http://equinocios.com/banco%20de%20dados/2017/03/30/persistencia-de-dados-usando-core-data/">&lt;blockquote&gt;
  &lt;p&gt;Olá pessoal, esse é meu primeiro artigo aqui no EquinociOS e então farei uma breve apresentação.
 Me chamo &lt;a href=&quot;https://twitter.com/bluesprogrammer&quot;&gt;Douglas Taquary&lt;/a&gt; sou desenvolvedor iOS um pouco mais de 3 anos, fundador e líder do Cocoaheads Teresina desde de 2015, nasci e me criei dentro da eletrônica do meu &lt;a href=&quot;https://www.facebook.com/profile.php?id=100009371490482&amp;amp;fref=ts&quot;&gt;Pai&lt;/a&gt; 📺🔌🔧 por isso a paixão também por IoT, eletrônica e seus derivados. Sou &lt;a href=&quot;https://www.youtube.com/watch?v=J0imW0Xu6nY&quot;&gt;guitarrista&lt;/a&gt; (apesar de não estar mais na atividade já algum tempo, somente vez ou outra), sou fã de blues, Jimi Hendrix,  e gosto de beber cerva e cozinhar ao mesmo tempo.
Feita essa introdução, vamos nessa: &lt;strong&gt;Core Data&lt;/strong&gt;!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;motivação&quot;&gt;Motivação&lt;/h2&gt;

&lt;p&gt;Há uns dois meses me deparei com uma situação em que precisaria persistir dados em um aplicativo. Eu nunca fui muito fã de trabalhar com banco de dados, talvez por experiências anteriores ou por causa de várias configurações chatas que você tem que fazer pra deixar tudo funcionando.
Acredito que em determinadas tecnologias, não era eu ou você quem deveria estar fazendo esse tipo de configuração(&lt;em&gt;o framework ou qualquer outra coisa que você esteja usando&lt;/em&gt;) tem que deixar tudo pronto somente para você ir lá e usar. Devo me preocupar com minha lógica de negócios, que no momento é o mais importante.&lt;/p&gt;

&lt;p&gt;Bom, mas o jeito foi engolir o choro. ¯\_(ツ)_/¯&lt;/p&gt;

&lt;h2 id=&quot;o-que-é-o-core-data&quot;&gt;O que é o Core Data&lt;/h2&gt;

&lt;p&gt;O &lt;a href=&quot;https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/index.html?utm_source=iosstash.io&quot;&gt;CoreData&lt;/a&gt; é um framework nativo como qualquer outro da &lt;strong&gt;Apple&lt;/strong&gt;: &lt;em&gt;UIKit, Foundation&lt;/em&gt; e alguns outros. Ele é usado para persistir, manipular dados no iOS/OSX e usa o &lt;code class=&quot;highlighter-rouge&quot;&gt;SQLite&lt;/code&gt; por baixo dos panos, mas você não precisar saber &lt;code class=&quot;highlighter-rouge&quot;&gt;SQL&lt;/code&gt; para usá-lo, ele interage com o &lt;em&gt;sql&lt;/em&gt; sem você ver ou precisar saber o que está acontecendo.
Usamos o esquema de &lt;em&gt;key/value&lt;/em&gt; para acessar nossos objetos persistidos.&lt;/p&gt;

&lt;p&gt;Algumas de várias características que esse framework possui:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Gerenciamento e manipulação de objetos(CRUD)&lt;/li&gt;
  &lt;li&gt;Buscas sofisticadas. Em vez de escrever SQL, você pode criar consultas complexas associando um objeto &lt;em&gt;NSPredicate&lt;/em&gt; a uma solicitação de busca.&lt;/li&gt;
  &lt;li&gt;Ferramentas de migração de esquema&lt;/li&gt;
  &lt;li&gt;Filtragem e gerenciamento de dados na memória e na interface de usuário&lt;/li&gt;
  &lt;li&gt;Controle de versão&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;E várias outras que você pode conferir &lt;a href=&quot;https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/index.html?utm_source=iosstash.io&quot;&gt;aqui&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Sei que existem outras tecnologias &lt;em&gt;open source&lt;/em&gt; como o &lt;code class=&quot;highlighter-rouge&quot;&gt;Realm&lt;/code&gt;, que também podem ser usadas para persistir dados no iOS e que podem ser adicionadas em seu projeto através do &lt;code class=&quot;highlighter-rouge&quot;&gt;CocoaPods&lt;/code&gt; ou via &lt;code class=&quot;highlighter-rouge&quot;&gt;módulo&lt;/code&gt;. Mas não é o intuito desse artigo falar sobre prós e contras de tecnologias. Cabe a você escolher a tecnologia que faz sentido no seu projeto.&lt;/p&gt;

&lt;p&gt;Blá, blá, blá… então vamos lá. 🎉&lt;/p&gt;

&lt;h2 id=&quot;explicando&quot;&gt;Explicando&lt;/h2&gt;

&lt;p&gt;Há um tempo atrás, como eu falei, eu criei um &lt;a href=&quot;https://github.com/douglastaquary/mymovies&quot;&gt;app&lt;/a&gt; para estudar o &lt;strong&gt;Core Data&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/douglastaquary/mymovies.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;O código do app ainda pode melhorar com algumas &lt;em&gt;refactors&lt;/em&gt; .&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;No app você pode inserir nomes de filmes favoritos, e pesquisar por eles através de uma &lt;em&gt;API&lt;/em&gt; chamada &lt;a href=&quot;http://www.omdbapi.com&quot;&gt;Open Movie Database&lt;/a&gt;. A ideia é salvar as informações sobre os filmes e poder vê-las offline, aqui que o &lt;em&gt;framework entra em ação&lt;/em&gt;. Nosso foco é somente o &lt;em&gt;Core Data&lt;/em&gt;. ;)&lt;/p&gt;

&lt;h2 id=&quot;vamos-lá&quot;&gt;Vamos lá&lt;/h2&gt;

&lt;p&gt;Para poder usar o &lt;em&gt;Core Data&lt;/em&gt; no seu projeto, é necessário habilitá-lo no Xcode no momento que você esta criando um novo projeto, mas ele pode ser adicionado também depois do projeto criado. Além disso, basta fazer &lt;code class=&quot;highlighter-rouge&quot;&gt;import CoreData&lt;/code&gt; do módulo nas suas classes e pronto. Isso será uma das poucas configurações que você precisará fazer para sair usando.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/douglastaquary/start_coredata.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Olha que maravilha?! Mais uma vez o &lt;em&gt;teorema do taquary&lt;/em&gt; agindo: nosso trabalho não é configurar, é usar, criar.. e blá, blá..&lt;/p&gt;

&lt;p&gt;Com projeto criado, abrindo a sua class &lt;code class=&quot;highlighter-rouge&quot;&gt;AppDelegate.swift&lt;/code&gt;, lá no final do arquivo tem uma variável chamada &lt;code class=&quot;highlighter-rouge&quot;&gt;var persistentContainer: NSPersistentContainer&lt;/code&gt;.
O Xcode cria essa implementação automaticamente. Ela é basicamente o meio de acesso ao seu banco de dados dentro do Core Data. Ele retorna um &lt;code class=&quot;highlighter-rouge&quot;&gt;container&lt;/code&gt; se seu banco de dados existe, caso contrário ele retornará um erro, o seu app &lt;code class=&quot;highlighter-rouge&quot;&gt;crasha&lt;/code&gt; e o Xcode imprime um &lt;code class=&quot;highlighter-rouge&quot;&gt;log&lt;/code&gt; no console.&lt;/p&gt;

&lt;p&gt;Somente isso que precisamos para criarmos nossas &lt;code class=&quot;highlighter-rouge&quot;&gt;queries&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Com a chegada do &lt;a href=&quot;&quot;&gt;Swift 3&lt;/a&gt; as coisas ficaram bem mais fáceis para se trabalhar com o &lt;em&gt;Core Data&lt;/em&gt;. Menos código e mais eficiência. Como eu disse, deixa o framework cuidar de configurações dele mesmo.&lt;/p&gt;

&lt;p&gt;Para mostrar o quanto se trabalhar com &lt;code class=&quot;highlighter-rouge&quot;&gt;Core Data&lt;/code&gt; depois do &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift 3&lt;/code&gt; melhorou eu tenho dois arquivos aqui que o &lt;em&gt;Xcode&lt;/em&gt; gera no &lt;code class=&quot;highlighter-rouge&quot;&gt;AppDelegate&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;O primeiro com &lt;strong&gt;Swift 2&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;kd&quot;&gt;lazy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;applicationDocumentsDirectory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSURL&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;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;urls&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSFileManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;defaultManager&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;kt&quot;&gt;URLsForDirectory&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;kt&quot;&gt;DocumentDirectory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;inDomains&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;kt&quot;&gt;UserDomainMask&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;urls&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;count&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;p&quot;&gt;}()&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;lazy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;managedObjectModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSManagedObjectModel&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;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;modelURL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSBundle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mainBundle&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;kt&quot;&gt;URLForResource&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;DATAMODELNAME&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;withExtension&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;momd&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;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSManagedObjectModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;contentsOfURL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;modelURL&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;c1&quot;&gt;// Create the coordinator and store&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;NSPersistentStoreCoordinator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;managedObjectModel&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;managedObjectModel&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;url&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;applicationDocumentsDirectory&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;URLByAppendingPathComponent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;PROJECTNAME.sqlite&quot;&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;failureReason&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;There was an error creating or loading the application's saved data.&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;do&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;coordinator&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;addPersistentStoreWithType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSSQLiteStoreType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;configuration&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;kt&quot;&gt;URL&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;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;kc&quot;&gt;nil&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;catch&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// Report any error we got.&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;dict&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;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AnyObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSLocalizedDescriptionKey&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;s&quot;&gt;&quot;Failed to initialize the application's saved data&quot;&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSLocalizedFailureReasonErrorKey&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;failureReason&lt;/span&gt;

            &lt;span class=&quot;n&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSUnderlyingErrorKey&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;error&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSError&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;wrappedError&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;domain&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;YOUR_ERROR_DOMAIN&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;code&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userInfo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;NSLog&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Unresolved error &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;wrappedError&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;wrappedError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userInfo&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;nf&quot;&gt;abort&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;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coordinator&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}()&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;lazy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;managedObjectContext&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSManagedObjectContext&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;c1&quot;&gt;// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;persistentStoreCoordinator&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;managedObjectContext&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSManagedObjectContext&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;concurrencyType&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;kt&quot;&gt;MainQueueConcurrencyType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;managedObjectContext&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;persistentStoreCoordinator&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;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;managedObjectContext&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Com &lt;strong&gt;Swift 3&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;kd&quot;&gt;lazy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;persistentContainer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPersistentContainer&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;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;container&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPersistentContainer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;CoreData_app&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;container&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;loadPersistentStores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;completionHandler&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;storeDescription&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&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;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;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSError&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;fatalError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Unresolved error &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userInfo&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;p&quot;&gt;}&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;container&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Que diferença hein?! Pois é… imagina isso em Objective C?! 🙏🏼&lt;/p&gt;

&lt;h2 id=&quot;criando-modelos&quot;&gt;Criando modelos&lt;/h2&gt;

&lt;p&gt;Outra coisa que podemos observar no nosso projeto, é que temos um arquivo com extensão &lt;code class=&quot;highlighter-rouge&quot;&gt;.xcdatamodel&lt;/code&gt; que no nosso caso, é chamado &lt;code class=&quot;highlighter-rouge&quot;&gt;CoreData_app.xcdatamodel&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/douglastaquary/tree2x.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Vamos analisar esse arquivo gerado, aqui criamos e gerenciamos nossas tabelas usando uma interface bem fácil e que poupa muito trabalho. Sem contar que quando você criar uma nova tabela &lt;code class=&quot;highlighter-rouge&quot;&gt;+ Add Entity&lt;/code&gt; e popular com seus atributos, assim que você &lt;code class=&quot;highlighter-rouge&quot;&gt;buildar&lt;/code&gt; seu projeto, o Xcode magicamente gera as classes referentes à &lt;em&gt;estrutura/esquema/modelo&lt;/em&gt; da sua tabela de dados criada. Olha que beleza 2! 🏄🏻&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Aqui os fãs de geradores de código piram&lt;/strong&gt; 😅&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;O &lt;em&gt;Xcode&lt;/em&gt; agora suporta a geração automática de subclasses de &lt;code class=&quot;highlighter-rouge&quot;&gt;NSManagedObject&lt;/code&gt; na ferramenta de modelagem.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Inspetor de entidade:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/douglastaquary/coredata_panel.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;o-mito-do-app-delegate&quot;&gt;O Mito do App Delegate&lt;/h2&gt;

&lt;p&gt;Já é de costume os &lt;code class=&quot;highlighter-rouge&quot;&gt;devs&lt;/code&gt; deixarem esse código onde Xcode o cria. Algo como: eu não vou nem tocar para não quebrar… Isso é &lt;strong&gt;MITO&lt;/strong&gt;!!😅
O melhor que você faz é tirar essa implementação do &lt;code class=&quot;highlighter-rouge&quot;&gt;AppDelegate&lt;/code&gt; e criar algo como &lt;code class=&quot;highlighter-rouge&quot;&gt;DataManager.swift&lt;/code&gt; e colar ele lá.&lt;/p&gt;

&lt;h2 id=&quot;nsmanagedobject&quot;&gt;NSManagedObject&lt;/h2&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;NSManagedObject&lt;/code&gt; é uma classe genérica que implementa todo o comportamento básico para um objeto no modelo que o Core Data espera. Não é possível usar instâncias de subclasses diretas de &lt;code class=&quot;highlighter-rouge&quot;&gt;NSObject&lt;/code&gt; (ou qualquer outra classe que não herde de &lt;code class=&quot;highlighter-rouge&quot;&gt;NSManagedObject&lt;/code&gt;) com um contexto de um objeto gerenciado.
Você pode criar subclasses customizadas do &lt;code class=&quot;highlighter-rouge&quot;&gt;NSManagedObject&lt;/code&gt;, embora isso nem sempre seja necessário, como eu falei o framework “&lt;em&gt;gera&lt;/em&gt;” as classes refente as suas tabelas e propriedades.🍺&lt;/p&gt;

&lt;h2 id=&quot;adicionar-dados&quot;&gt;Adicionar Dados&lt;/h2&gt;

&lt;p&gt;No app temos um tela para inserir títulos de filmes. Então, precisamos persistir um atributo &lt;em&gt;name&lt;/em&gt; do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; na tabela &lt;code class=&quot;highlighter-rouge&quot;&gt;Title&lt;/code&gt;. Para eu inserir essa informação, eu simplesmente carrego meu &lt;code class=&quot;highlighter-rouge&quot;&gt;persistentContainer&lt;/code&gt; através da minha classe &lt;code class=&quot;highlighter-rouge&quot;&gt;DataManager&lt;/code&gt; no meu &lt;code class=&quot;highlighter-rouge&quot;&gt;ViewController&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;var dataManager = DataManager()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;e implemento minha função para inserir dados:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;saveNameOfMovie&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;name&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;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;managedContext&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;persistentContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;viewContext&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;entity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSEntityDescription&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;entity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;forEntityName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Title&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;managedContext&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;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;movie&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSManagedObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;entity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;entity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;insertInto&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;managedContext&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;movie&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;setValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;forKey&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;do&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;managedContext&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;nf&quot;&gt;didEnd&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;catch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSError&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;Could not save. &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userInfo&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;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;p&gt;Aqui nós instanciamos nosso container usando o &lt;code class=&quot;highlighter-rouge&quot;&gt;managedContext&lt;/code&gt;, depois pegamos a referência da tabela(&lt;em&gt;você pode ter várias tabelas&lt;/em&gt;) com &lt;code class=&quot;highlighter-rouge&quot;&gt;entity&lt;/code&gt; e criamos o objeto que será persistido:&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;let name = NSManagedObject(entity: entity, insertInto: managedContext)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;E aí eu salvo de fato meu dado usando a funcão &lt;code class=&quot;highlighter-rouge&quot;&gt;save()&lt;/code&gt; padrão do framework.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;try managedContext.save()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Tranquilo demais!&lt;/p&gt;

&lt;h2 id=&quot;nsfetchrequest&quot;&gt;NSFetchRequest&lt;/h2&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;NSFetchRequest&lt;/code&gt; é um &lt;em&gt;tipo parametrizado&lt;/em&gt; baseado no novo protocolo &lt;code class=&quot;highlighter-rouge&quot;&gt;NSFetchRequestResult&lt;/code&gt; adicionado no &lt;em&gt;Swift 3&lt;/em&gt;. As principais &lt;em&gt;APIs do Core Data&lt;/em&gt; agora se referem a &lt;code class=&quot;highlighter-rouge&quot;&gt;NSFetchRequest&lt;/code&gt; &lt;em&gt;parametrizado&lt;/em&gt; no &lt;code class=&quot;highlighter-rouge&quot;&gt;Objective C&lt;/code&gt; e no &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Além disso, no &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;NSManagedObjectContext&lt;/code&gt; oferece variantes parametrizadas de &lt;code class=&quot;highlighter-rouge&quot;&gt;fetch(:)&lt;/code&gt;, que antes do Swift 3 era chamado de &lt;code class=&quot;highlighter-rouge&quot;&gt;executeFetchRequest: error:&lt;/code&gt;, e &lt;code class=&quot;highlighter-rouge&quot;&gt;count(:)&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fetch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSFetchRequestResult&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;request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSFetchRequest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&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;k&quot;&gt;throws&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;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;count&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSFetchRequestResult&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;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSFetchRequest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&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;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;Int&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;É com ele que vamos recuperar nossos dados. 🍷&lt;/p&gt;

&lt;h2 id=&quot;listar-nossos-dados&quot;&gt;Listar nossos dados&lt;/h2&gt;

&lt;p&gt;Para a minha &lt;code class=&quot;highlighter-rouge&quot;&gt;tableview&lt;/code&gt; mostrar meus registros de filmes favoritos é mais simples ainda.&lt;/p&gt;

&lt;p&gt;Para recuperar os dados persistidos, nós usamos a instância de  &lt;code class=&quot;highlighter-rouge&quot;&gt;NSFetchRequest&lt;/code&gt;, onde temos que passar o nome da tabela.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;loadData&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;fetchRequest&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSFetchRequest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSFetchRequestResult&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;nv&quot;&gt;entityName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Title&quot;&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;context&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;persistentContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;viewContext&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;do&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;results&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;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fetch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fetchRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;namesOfMovies&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as!&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NSManagedObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;tableView&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reloadData&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;catch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;fatalError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Error is retriving titles items&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;p&quot;&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Depois eu chamo a funcão &lt;code class=&quot;highlighter-rouge&quot;&gt;fetch()&lt;/code&gt; usando o &lt;code class=&quot;highlighter-rouge&quot;&gt;context&lt;/code&gt; e passando o &lt;code class=&quot;highlighter-rouge&quot;&gt;fetchRequest&lt;/code&gt; como parâmetro.&lt;/p&gt;

&lt;p&gt;Dai é só transformar o resultado da sua busca em uma &lt;code class=&quot;highlighter-rouge&quot;&gt;array&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;[NSManagedObject]&lt;/code&gt;, nesse caso, atribuído à &lt;em&gt;variável&lt;/em&gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;namesOfMovies&lt;/code&gt; e dar reload na &lt;code class=&quot;highlighter-rouge&quot;&gt;tableview&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Então lá na função &lt;code class=&quot;highlighter-rouge&quot;&gt;cellForRowAt&lt;/code&gt; da &lt;code class=&quot;highlighter-rouge&quot;&gt;tableView&lt;/code&gt; eu consigo fazer isso:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;cell&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&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;n&quot;&gt;nameOfMovie&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;forKey&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&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;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;e listar meus objetos persistidos, moleza hein?!&lt;/p&gt;

&lt;p&gt;Bom, então é isso, essa foi uma breve introdução.&lt;/p&gt;

&lt;p&gt;Existem muito mais operações que podem ser feitas com esse poderoso framework nativo que está ali, só no ponto pra você usar. Espero que esse artigo tenha ajudado você a entender melhor o &lt;code class=&quot;highlighter-rouge&quot;&gt;Core Data&lt;/code&gt; e algumas de suas estruturas.
Quem sabe em um próximo podemos ir mais a fundo e brincar um pouco mais com ele.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Quer saber mais&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://developer.apple.com/reference/coredata&quot;&gt;Core Data documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://developer.apple.com/library/content/releasenotes/General/WhatNewCoreData2016/ReleaseNotes.html&quot;&gt;What`s New In Core Data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/index.html?utm_source=iosstash.io&quot;&gt;What Is Core Data?&lt;/a&gt;&lt;/p&gt;</content><author><name>Douglas Taquary</name></author><category term="Banco de Dados" /><summary type="html">Olá pessoal, esse é meu primeiro artigo aqui no EquinociOS e então farei uma breve apresentação. Me chamo Douglas Taquary sou desenvolvedor iOS um pouco mais de 3 anos, fundador e líder do Cocoaheads Teresina desde de 2015, nasci e me criei dentro da eletrônica do meu Pai 📺🔌🔧 por isso a paixão também por IoT, eletrônica e seus derivados. Sou guitarrista (apesar de não estar mais na atividade já algum tempo, somente vez ou outra), sou fã de blues, Jimi Hendrix, e gosto de beber cerva e cozinhar ao mesmo tempo. Feita essa introdução, vamos nessa: Core Data!</summary></entry><entry><title type="html">Interfaces assíncronas com AsyncDisplayKit</title><link href="http://equinocios.com/ui/2017/03/29/introducao-ao-asyncdisplaykit-construa-interfaces-asyncronas-no-iOS/" rel="alternate" type="text/html" title="Interfaces assíncronas com AsyncDisplayKit" /><published>2017-03-29T12:00:00+00:00</published><updated>2017-03-29T12:00:00+00:00</updated><id>http://equinocios.com/ui/2017/03/29/introducao%20ao%20asyncdisplaykit%20-%20construa%20interfaces%20asyncronas%20no%20iOS</id><content type="html" xml:base="http://equinocios.com/ui/2017/03/29/introducao-ao-asyncdisplaykit-construa-interfaces-asyncronas-no-iOS/">&lt;blockquote&gt;
  &lt;p&gt;Sou o Guga Oliveira (&lt;a href=&quot;https://twitter.com/gugaoliveira&quot; target=&quot;_blank&quot;&gt;@gugaoliveira&lt;/a&gt;), empreendedor, cursei engenharia eletrônica mas sempre trabalhei com softwares e programação. Abri uma empresa de desenvolvimento Web em Juiz de Fora no início de 2000, e em 2007 fundamos a &lt;a href=&quot;http://www.handcom.com.br&quot; target=&quot;_blank&quot;&gt;Handcom&lt;/a&gt; focada em mobilidade. Trabalhamos com iOS desde o início, e criamos aplicativos em sua maioria focados no varejo e com foco empresarial. Em 2014 fundamos a startup &lt;a href=&quot;http://www.microlocation.com.br&quot; target=&quot;_blank&quot;&gt;Microlocation&lt;/a&gt; que foi acelerada pelo Seed-MG e hoje faz parte de nossa solução para o varejo &lt;a href=&quot;http://www.smartretail.com.br&quot; target=&quot;_blank&quot;&gt;Smart-Retail&lt;/a&gt;, atualmente estou estudando Swift e Análise de Dados, e participando bastante do desenvolvimento dos ecossistemas de Minas Gerais com o MGTI em BH e o Zer040 em Juiz de Fora.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;interface-assíncrona-sem-interface-builder&quot;&gt;interface assíncrona? sem Interface Builder?&lt;/h2&gt;

&lt;p&gt;Fui apresentado ao &lt;a href=&quot;http://asyncdisplaykit.org/&quot;&gt;AsyncDisplayKit&lt;/a&gt; pelo Heberti Almeida, excelente dev iOS que conheci na WWDC de 2013. Ele estava usando o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; no desenvolvimento do novo app da &lt;a href=&quot;https://postbeyond.com&quot; target=&quot;_blank&quot;&gt;PostBeyond&lt;/a&gt;, startup em que ele trabalha. No começo achei complicado apostar em uma biblioteca de terceiros para substituir as bibliotecas próprias do iOS como &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt;, XIBs e Storyboards.&lt;/p&gt;

&lt;p&gt;Mas na WWDC 2016, o Heberti me convidou para ir no evento do &lt;a href=&quot;http://www.pinterest.com&quot; target=&quot;_blank&quot;&gt;Pinterest&lt;/a&gt; que acontecia em volta da WWDC. O evento foi promovido pelo Scott Goodsom &lt;a href=&quot;https://twitter.com/ScottGoodson&quot; target=&quot;_blank&quot;&gt;@ScottGoodson&lt;/a&gt;, que é Head of Core Experience no Pinterest, e que idealizou a &lt;em&gt;AsyncDisplayKit&lt;/em&gt; para desenvolver o &lt;em&gt;Paper&lt;/em&gt; para o &lt;em&gt;Facebook&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8ngXakpE2x8&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;https://img.youtube.com/vi/8ngXakpE2x8/0.jpg&quot; alt=&quot;WWDC 2016 AsyncDisplayKit event &quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;em&gt;WWDC 2016 AsyncDisplayKit event&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;O que vi no evento me surpreendeu bastante, engenheiros de apps famosos utilizando intensamente a biblioteca, com foco total em performance visual. O &lt;em&gt;Pinterest&lt;/em&gt; utiliza o &lt;em&gt;AsyncDisplayKit&lt;/em&gt; e possui engenheiros trabalhando de forma obsessiva na engenharia de renderização das telas para que fiquem extremamente responsivas, com o mínimo &lt;em&gt;drop&lt;/em&gt; de &lt;em&gt;frames&lt;/em&gt; possível.&lt;/p&gt;

&lt;p&gt;Como nosso aplicativo possui uma tela com muitas imagens de produtos e um fluxo quase infinito, como em uma timeline de produtos, resolvemos apostar na re-escrita com o AsyncDisplayKit nas próximas versões, além de quebrar um grande paradigma na empresa, que é o uso de Storyboard e Interface Builder.&lt;/p&gt;

&lt;p&gt;Como é um framework complexo, e não por isso difícil de usar, este artigo pretende ser introdutório ao AsyncDisplayKit, tentarei complementar com assuntos mais avançados em breve.&lt;/p&gt;

&lt;h2 id=&quot;asyncdisplaykit&quot;&gt;AsyncDisplayKit&lt;/h2&gt;

&lt;p&gt;O &lt;a href=&quot;https://github.com/facebook/AsyncDisplayKit&quot; target=&quot;_blank&quot;&gt;AsyncDisplayKit&lt;/a&gt; é uma framework Open Source iOS feito no topo do UIKit com o objetivo de deixar até as interfaces visuais mais complexas com fluxo suave e responsivo. O Framework é &lt;em&gt;Open Source&lt;/em&gt; e está disponível via CocoaPods ou Carthage.&lt;/p&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt; é um dos frameworks mais maduros do iOS, e foi desenvolvido quando os iPhones tinham recursos restritos de sistema, no início nem existia possibilidade de utilizar códigos assíncronos concorrentes. O problema é que mesmo atualmente o &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt; roda em uma única &lt;em&gt;thread&lt;/em&gt; e só funciona na &lt;em&gt;main queue&lt;/em&gt;. Na maior parte dos casos funciona bem, mas quando envolve interfaces mais complexas ou necessita-se de mais recursos, a interface acaba não sendo tão responsiva. Para estes casos, trabalhar de forma assíncrona é extremamente necessário para criar uma interface lisa e responsiva com o usuário.&lt;/p&gt;

&lt;p&gt;O iOS renderiza a interface com o usuário em 60 frames por segundo, o que nos dá apenas 16 milisegundos de CPU por frame, e caso você ultrapasse este mínimo intervalo de tempo o sistema operacional vai começar a liberar drop de frames imediatamente, tornando nossa interface muito menos responsiva e suave, principalmente agora que muitos apps utilizam de animações e efeitos para obter a atenção do usuário.&lt;/p&gt;

&lt;p&gt;E nos tempos de autolayout e animações, existem várias tarefas para a &lt;em&gt;main thread&lt;/em&gt; realizar e consumir o pequeno tempo de frame que temos, como calcular a dimensão automática de cada célula, resolver os &lt;em&gt;constraints&lt;/em&gt; dos conteúdos das views, renderizar e decodificar imagens, criar sombras e contornos, efeitos como blur e shadow, redimensionamento de imagens para exibição e criação e manipulação de objetos do sistema.&lt;/p&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; (&lt;em&gt;AsyncDisplayKit&lt;/em&gt;) chegou para resolver esses problemas, ele move o máximo de trabalho de &lt;code class=&quot;highlighter-rouge&quot;&gt;UI&lt;/code&gt; para ser executado em &lt;em&gt;background&lt;/em&gt;. Por default ele permite que todas os cálculos de medidas, estruturações layout e renderizações sejam feitas de forma assíncrona, sem muitas otimizações um app pode experimentar uma grande redução do trabalho realizado na &lt;em&gt;main thread&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; é incompatível com &lt;strong&gt;&lt;em&gt;Interface Builder&lt;/em&gt;&lt;/strong&gt; e &lt;strong&gt;&lt;em&gt;Auto Layout&lt;/em&gt;&lt;/strong&gt;, a biblioteca foi escrita em &lt;em&gt;Objective-C&lt;/em&gt;, mas o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; suporta completamente o &lt;em&gt;Swift&lt;/em&gt; .&lt;/p&gt;

&lt;h3 id=&quot;começando&quot;&gt;Começando&lt;/h3&gt;

&lt;p&gt;A unidade fundamental do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; é o &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt; ou &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDisplayNode&lt;/code&gt;, ele é uma abstração da &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt;, que por conseguinte é uma abstração da &lt;code class=&quot;highlighter-rouge&quot;&gt;CALayer&lt;/code&gt;. A &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt; só pode ser manipulada na &lt;em&gt;main thread&lt;/em&gt;, mas os &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; são &lt;em&gt;thread safe&lt;/em&gt; e podem ser instanciados e ter toda sua hierarquia configurada em &lt;em&gt;background&lt;/em&gt; .&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/gugaoliveira/node-view-layer.png&quot; alt=&quot;Node - View - Layer&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A idéia básica do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; é que você possa trabalhar com os &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; da mesma forma como já trabalha com as &lt;code class=&quot;highlighter-rouge&quot;&gt;views&lt;/code&gt;, a grande maioria dos métodos e parâmetros da &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt; e da &lt;code class=&quot;highlighter-rouge&quot;&gt;CALayer&lt;/code&gt; possuem equivalentes nos &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Tudo o que aparece na tela do iOS é renderizado por um objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;CALayer&lt;/code&gt;, a &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt; cria e mantém a referência do objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;CALayer&lt;/code&gt;, e os &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; extendem a &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt; da mesma forma, como na imagem acima. Você pode acessar a &lt;em&gt;view&lt;/em&gt; e o &lt;em&gt;layer&lt;/em&gt; que estão abaixo diretamente com &lt;code class=&quot;highlighter-rouge&quot;&gt;node.view&lt;/code&gt; e &lt;code class=&quot;highlighter-rouge&quot;&gt;node.layer&lt;/code&gt;, desde que esteja na &lt;em&gt;main thread&lt;/em&gt;.&lt;/p&gt;

&lt;h4 id=&quot;containers-de-nodes&quot;&gt;Containers de nodes&lt;/h4&gt;

&lt;p&gt;Os &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; devem ser usados dentro de &lt;em&gt;containers&lt;/em&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt;, o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; oferece alguns &lt;em&gt;containers&lt;/em&gt;  que tem similares com classes do &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt; que estamos acostumados a trabalhar. Um &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt; não deve ser adicionado diretamente a uma hirerarquia de &lt;code class=&quot;highlighter-rouge&quot;&gt;view&lt;/code&gt; (se fizer isso é quase certo de você obter piscadas de tela). Um &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt; deve ser adicionado como subnode de um &lt;em&gt;container&lt;/em&gt; de nodes. Esses &lt;em&gt;containers&lt;/em&gt; possuem a tarefa de gerenciar os subnodes para informá-los se está tudo pronto para renderizar na tela de forma mais eficiente possível.&lt;/p&gt;

&lt;p&gt;Uma vantagem do uso dos &lt;em&gt;containers&lt;/em&gt;  de &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; é que o &lt;em&gt;container&lt;/em&gt; automaticamente gerencia o pre-loading inteligente (&lt;em&gt;Inteligent Preloading&lt;/em&gt;) dos &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; (&lt;code class=&quot;highlighter-rouge&quot;&gt;views&lt;/code&gt;), que significa que toda tarefa de medição do layout, de carregamento de dados, decodificação e renderização serão feitos de forma assíncrona automaticamente.&lt;/p&gt;

&lt;p&gt;Os principais containers estão abaixo com os equivalentes no &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Container &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Equivalente &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;http://asyncdisplaykit.org/docs/containers-asviewcontroller.html&quot; target=&quot;_blank&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ASViewController&lt;/code&gt;&lt;/a&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;UIViewController&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;http://asyncdisplaykit.org/docs/containers-astablenode.html&quot; target=&quot;_blank&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ASTableNode&lt;/code&gt;&lt;/a&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;UITableView&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;http://asyncdisplaykit.org/docs/containers-ascollectionnode.html&quot; target=&quot;_blank&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ASCollectionNode&lt;/code&gt;&lt;/a&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;UICollectionView&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;http://asyncdisplaykit.org/docs/containers-aspagernode.html&quot; target=&quot;_blank&quot;&gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;ASPagerNode&lt;/code&gt;&lt;/a&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;UIPageViewController&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ASNavigationController&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;UINavigationController&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ASTabBarController &lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;UITabBarController &lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;layout-engine&quot;&gt;Layout Engine&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;&lt;em&gt;Layout Engine&lt;/em&gt;&lt;/strong&gt; do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; é muito poderosa e oferece recursos únicos, ela é baseada no &lt;code class=&quot;highlighter-rouge&quot;&gt;CSS Box Model&lt;/code&gt;, e fornece formas de declarar e especificar o tamanho e posição dos &lt;code class=&quot;highlighter-rouge&quot;&gt;subnodes&lt;/code&gt;. Os &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; (&lt;code class=&quot;highlighter-rouge&quot;&gt;views&lt;/code&gt;) são renderizados de forma concorrente por default, mas os cálculos de medidas e posição são executados de forma assíncrona ao se usar um &lt;code class=&quot;highlighter-rouge&quot;&gt;ASLayoutSpec&lt;/code&gt; para cada &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt;. Aqui está a maior diferença entre o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; e o &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt;, no &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; o layout é declarativo e no &lt;code class=&quot;highlighter-rouge&quot;&gt;UIKit&lt;/code&gt; é baseado em &lt;em&gt;constraint&lt;/em&gt; com o &lt;code class=&quot;highlighter-rouge&quot;&gt;Auto Layout&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;&lt;em&gt;Layout Engine&lt;/em&gt;&lt;/strong&gt; será assunto de um segundo artigo que sairá em breve, no entanto no fim do artigo deixarei referências.&lt;/p&gt;

&lt;h3 id=&quot;instalando&quot;&gt;Instalando&lt;/h3&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; pode ser adicionado ao seu projeto via CocoaPods ou Carthage.&lt;/p&gt;

&lt;h4 id=&quot;cocoapods&quot;&gt;CocoaPods&lt;/h4&gt;
&lt;p&gt;Adicione o seguinte comando no seu &lt;code class=&quot;highlighter-rouge&quot;&gt;Podfile&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;target 'MyApp' do
	pod &quot;AsyncDisplayKit&quot;
end
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Saia do &lt;code class=&quot;highlighter-rouge&quot;&gt;XCode&lt;/code&gt;, rode o comando dentro do diretório do projeto no Terminal:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; pod install
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Para atualizar a versão do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;, rode o comando dentro do diretório do projeto no Terminal:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; pod update AsyncDisplayKit
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h4 id=&quot;carthage&quot;&gt;Carthage&lt;/h4&gt;
&lt;p&gt;Adicione o seguinte comando no seu &lt;code class=&quot;highlighter-rouge&quot;&gt;Cartfile&lt;/code&gt; para usar a &lt;strong&gt;&lt;em&gt;última versão&lt;/em&gt;&lt;/strong&gt; do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;github &quot;facebook/AsyncDisplayKit&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Ou para usar a branch &lt;strong&gt;&lt;em&gt;master&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;github &quot;facebook/AsyncDisplayKit&quot; &quot;master&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;No terminal rode:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; carthage update
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Verifique no terminal se &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncDisplayKit&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;PINRemoteImage&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;PINCache&lt;/code&gt; foram carregadas e compiladas.&lt;/p&gt;

&lt;h3 id=&quot;importando-o-framework&quot;&gt;importando o framework&lt;/h3&gt;

&lt;p&gt;Importe o header do framework para usá-lo&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-objective-c&quot;&gt;#import &amp;lt;AsyncDisplayKit/AsyncDisplayKit.h&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Para usar com &lt;code class=&quot;highlighter-rouge&quot;&gt;swift&lt;/code&gt; deve-se criar um &lt;a href=&quot;https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;bridge header&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;mão-na-massa&quot;&gt;Mão na massa&lt;/h2&gt;

&lt;p&gt;A melhor maneira para iniciar é explorar os projetos de exemplo existentes no &lt;a href=&quot;https://github.com/facebook/AsyncDisplayKit&quot; target=&quot;_blank&quot;&gt;GitHub&lt;/a&gt; do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;. A pasta &lt;strong&gt;&lt;em&gt;examples&lt;/em&gt;&lt;/strong&gt; possui diversos exemplos, inclusive um simulando o Instagram chamado ASDKgram.&lt;/p&gt;

&lt;p&gt;Vamos usar o exemplo ASViewController em Objective-c para nosso exemplo:&lt;/p&gt;

&lt;p align=&quot;center&quot;&gt;&lt;img style=&quot;border-radius: 3px;&quot; src=&quot;/img/gugaoliveira/ASViewController.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Para criar uma equivalente de &lt;code class=&quot;highlighter-rouge&quot;&gt;ViewController&lt;/code&gt; vamos usar o container &lt;code class=&quot;highlighter-rouge&quot;&gt;ASViewController&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-objective-c&quot;&gt;@interface ViewController : ASViewController
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nossa &lt;code class=&quot;highlighter-rouge&quot;&gt;ViewController&lt;/code&gt; contem uma &lt;code class=&quot;highlighter-rouge&quot;&gt;TableView&lt;/code&gt; que irá exibir as categorias de Imagens disponíveis para visualização, vamos então implementar a &lt;code class=&quot;highlighter-rouge&quot;&gt;TableView&lt;/code&gt; usando o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASTableNode&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Declarando o array que contem os nomes da categoria e o &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt; que reprensenta a &lt;code class=&quot;highlighter-rouge&quot;&gt;TableView&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-objective-c&quot;&gt;@property (nonatomic, copy) NSArray *imageCategories;
@property (nonatomic, strong, readonly) ASTableNode *tableNode;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Vamos configurar a &lt;code class=&quot;highlighter-rouge&quot;&gt;ViewController&lt;/code&gt;, iniciando a &lt;code class=&quot;highlighter-rouge&quot;&gt;TableNode&lt;/code&gt; e o &lt;code class=&quot;highlighter-rouge&quot;&gt;array&lt;/code&gt; usando o &lt;code class=&quot;highlighter-rouge&quot;&gt;initWithNode&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-objective-c&quot;&gt;- (instancetype)init
{
    self = [super initWithNode:[ASTableNode new]];
    if (self == nil) { return self; }
    
    _imageCategories = @[@&quot;abstract&quot;, @&quot;animals&quot;, @&quot;business&quot;, @&quot;cats&quot;, @&quot;city&quot;, @&quot;food&quot;, @&quot;nightlife&quot;, @&quot;fashion&quot;, @&quot;people&quot;, @&quot;nature&quot;, @&quot;sports&quot;, @&quot;technics&quot;, @&quot;transport&quot;];
    
    return self;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Assim como na &lt;code class=&quot;highlighter-rouge&quot;&gt;TableView&lt;/code&gt; para usar o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASTableNode&lt;/code&gt; deveremos nos conformar ao &lt;code class=&quot;highlighter-rouge&quot;&gt;delegate&lt;/code&gt; e ao &lt;code class=&quot;highlighter-rouge&quot;&gt;datasource&lt;/code&gt; da &lt;em&gt;TableNode&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-objective-c&quot;&gt;....

@interface ViewController () &amp;lt;ASTableDataSource, ASTableDelegate&amp;gt;

.....

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    ...
    
    self.node.delegate = self;
    self.node.dataSource = self;
}

....
- (void)dealloc
{
    self.node.delegate = nil;
    self.node.dataSource = nil;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Agora vamos implementar os &lt;code class=&quot;highlighter-rouge&quot;&gt;delegates&lt;/code&gt; e &lt;code class=&quot;highlighter-rouge&quot;&gt;datasource&lt;/code&gt; da &lt;code class=&quot;highlighter-rouge&quot;&gt;TableNode&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-Objective-c&quot;&gt;- (NSInteger)tableNode:(ASTableNode *)tableNode numberOfRowsInSection:(NSInteger)section
{
    return self.imageCategories.count;
}

- (ASCellNodeBlock)tableNode:(ASTableNode *)tableNode nodeBlockForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Como o bloco é executado em outra thread em background temos que armazenar a imageCategory fora do bloco 
    NSString *imageCategory = self.imageCategories[indexPath.row];
    return ^{
        ASTextCellNode *textCellNode = [ASTextCellNode new];
        textCellNode.text = [imageCategory capitalizedString];
        return textCellNode;
    };
}

- (void)tableNode:(ASTableNode *)tableNode didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *imageCategory = self.imageCategories[indexPath.row];
    DetailRootNode *detailRootNode = [[DetailRootNode alloc] initWithImageCategory:imageCategory];
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNode:detailRootNode];
    detailViewController.title = [imageCategory capitalizedString];
    [self.navigationController pushViewController:detailViewController animated:YES];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Reparem que os métodos são bem similares aos da &lt;code class=&quot;highlighter-rouge&quot;&gt;UITableView&lt;/code&gt;, a &lt;code class=&quot;highlighter-rouge&quot;&gt;ASTextCellNode&lt;/code&gt; é uma subclasse de &lt;code class=&quot;highlighter-rouge&quot;&gt;ASCellNode&lt;/code&gt;, que é o equivalente do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; a &lt;code class=&quot;highlighter-rouge&quot;&gt;UITableViewCell&lt;/code&gt; ou &lt;code class=&quot;highlighter-rouge&quot;&gt;UICollectionViewCell&lt;/code&gt;. No caso a &lt;code class=&quot;highlighter-rouge&quot;&gt;ASTextCellNode&lt;/code&gt; possui um label simples para exibição de texto. Mas existe uma diferença no método de exibição da célula.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-Objective-C&quot;&gt;
//UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

//ASTableNode
- (ASCellNodeBlock)tableNode:(ASTableNode *)tableNode nodeBlockForRowAtIndexPath:(NSIndexPath *)indexPath
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A diferença aqui é que o retorno é um bloco de código que pode ser executado em background pelo &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;, neste caso a variável &lt;code class=&quot;highlighter-rouge&quot;&gt;indexPath&lt;/code&gt; não pode ser usada dentro do bloco, pois os dados podem mudar antes do bloco ser executado. Não é necessário reusar as celulas, o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; faz o trabalho para você, basta iniciar o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASCellNode&lt;/code&gt; e retorná-lo ao fim do bloco.&lt;/p&gt;

&lt;p&gt;Ao se selecionar uma linha da &lt;code class=&quot;highlighter-rouge&quot;&gt;TableNode&lt;/code&gt; instanciamos a classe &lt;strong&gt;&lt;em&gt;DetailRootNode&lt;/em&gt;&lt;/strong&gt;, que é uma subclasse de &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDisplayNode&lt;/code&gt; (o node fundamental do &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;), com o inicializador que recebe o nome da categoria de imagens, depois instanciamos a &lt;strong&gt;&lt;em&gt;DetailViewController&lt;/em&gt;&lt;/strong&gt; que é uma subclasse de &lt;code class=&quot;highlighter-rouge&quot;&gt;ASViewController&lt;/code&gt; com o &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt; &lt;strong&gt;&lt;em&gt;DetailRootControler&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Na &lt;strong&gt;&lt;em&gt;DetailRootNode&lt;/em&gt;&lt;/strong&gt; temos uma instância de &lt;code class=&quot;highlighter-rouge&quot;&gt;ASCollectionNode&lt;/code&gt; o &lt;em&gt;container&lt;/em&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;nodes&lt;/code&gt; que é equivalente a &lt;code class=&quot;highlighter-rouge&quot;&gt;UIViewController&lt;/code&gt;. Aqui vamos usar a capacidade de um &lt;code class=&quot;highlighter-rouge&quot;&gt;node&lt;/code&gt; gerenciar os &lt;code class=&quot;highlighter-rouge&quot;&gt;subnodes&lt;/code&gt;, automaticamente o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; irá adicionar a &lt;code class=&quot;highlighter-rouge&quot;&gt;CollectionView&lt;/code&gt; à view &lt;strong&gt;&lt;em&gt;DetailRootNode&lt;/em&gt;&lt;/strong&gt; que é adicionada à DetailViewController.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-Objective-C&quot;&gt;// DetailRootNode é um ASDisplayNode
@interface DetailRootNode : ASDisplayNode

//o ASDisplayNode possui uma ASCollectionNode (equivalente UIViewCollection)
@property (nonatomic, strong, readonly) ASCollectionNode *collectionNode;

....

// conforma-se os delegates e datasource da ASCollectionView

@interface DetailRootNode () &amp;lt;ASCollectionDataSource, ASCollectionDelegate&amp;gt;

....

- (instancetype)initWithImageCategory:(NSString *)imageCategory
{
    self = [super init];
    if (self) {
        // Habilita o gerenciamento automatico dos subnodes todos os nodes que 
        // estiverem referenciados no metodo layoutSpecThatFits: serão adicionados automaticamente
        self.automaticallyManagesSubnodes = YES;
        
        _imageCategory = imageCategory;

        // Cria a ASCollectionView. Não é necessário adicionar como subnode explicitamente por que iremos configurar o parametro usesImplicitHierarchyManagement para YES
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionNode = [[ASCollectionNode alloc] initWithCollectionViewLayout:layout];
        _collectionNode.delegate = self;
        _collectionNode.dataSource = self;
        _collectionNode.backgroundColor = [UIColor whiteColor];
    }
    
    return self;
}

... 

// adiciona e calcula automaticamente as dimensoes do DisplayNode com a CollectionView
- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
    return [ASWrapperLayoutSpec wrapperWithLayoutElement:self.collectionNode];
}

...

#pragma mark - ASCollectionDataSource

- (NSInteger)collectionNode:(ASCollectionNode *)collectionNode numberOfItemsInSection:(NSInteger)section
{
    return 10;
}

- (ASCellNodeBlock)collectionNode:(ASCollectionNode *)collectionNode nodeBlockForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *imageCategory = self.imageCategory;
    return ^{
        DetailCellNode *node = [[DetailCellNode alloc] init];
        node.row = indexPath.row;
        node.imageCategory = imageCategory;
        return node;
    };
}

- (ASSizeRange)collectionNode:(ASCollectionNode *)collectionNode constrainedSizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize imageSize = CGSizeMake(CGRectGetWidth(collectionNode.view.frame), kImageHeight);
    return ASSizeRangeMake(imageSize, imageSize);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Como podem perceber a &lt;code class=&quot;highlighter-rouge&quot;&gt;ViewController&lt;/code&gt; &lt;strong&gt;&lt;em&gt;DetailViewController&lt;/em&gt;&lt;/strong&gt; é criada com uma view que contem uma &lt;code class=&quot;highlighter-rouge&quot;&gt;CollectionView&lt;/code&gt;, esta carrega 10 imagens de uma api em cada célula. A &lt;strong&gt;&lt;em&gt;DetailCellNode&lt;/em&gt;&lt;/strong&gt; é uma CollectionViewCell que é configurada em um bloco carregado em background pelo &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; após as imagens serem carregadas. A &lt;code class=&quot;highlighter-rouge&quot;&gt;UI&lt;/code&gt; em nenhum momento deixa de ser responsível ou fluida.&lt;/p&gt;

&lt;h2 id=&quot;terminando&quot;&gt;Terminando&lt;/h2&gt;

&lt;p&gt;Este é um exemplo simples que demonstra como é intuitivo e fácil trabalhar com o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt;, existem muitos tópicos avançados de como melhorar ainda mais a performance. Neste artigo não pudemos falar sobre Layout, Inteligent Preloading e outras conveniências. Ele serve como um start para a avaliação da biblioteca como substituta do UIKit para criar interfaces mais fluidas e responsivas.&lt;/p&gt;

&lt;p&gt;Agradeço a leitura e fico aberto a sugestões e críticas, este foi o meu primeiro artigo de desenvolvimento, e pretendo escrever mais.&lt;/p&gt;

&lt;p&gt;Seguem meus contatos:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://twitter.com/gugaoliveira&quot; target=&quot;_blank&quot;&gt;Twitter (@gugaoliveira)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Slack do &lt;a href=&quot;http://iosdevbr.herokuapp.com/&quot; target=&quot;_blank&quot;&gt;iOSDevBR&lt;/a&gt; (@gugaoliveira).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Agradecimentos especiais ao &lt;a href=&quot;https://twitter.com/hebertialmeida&quot; target=&quot;_blank&quot;&gt;Heberti Almeida&lt;/a&gt;, que já utiliza o &lt;code class=&quot;highlighter-rouge&quot;&gt;ASDK&lt;/code&gt; há bastante tempo e me apresentou esta biblioteca fantástica e também seus criadores, foi realmente bacana poder conversar com os criadores e ter uma canal de comunicação direta.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;referências&quot;&gt;Referências&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://asyncdisplaykit.org/docs/getting-started.html&quot; target=&quot;_blank&quot;&gt;AsyncDisplayKit Getting Starded&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://www.appcoda.com/introduction-asyncdisplaykit-2-0/&quot; target=&quot;_blank&quot;&gt;Using AsyncDisplayKit to Develop Responsive UIs in iOS&lt;/a&gt; &lt;strong&gt;&lt;em&gt;[Ziad Tamim, 29/12/2016]&lt;/em&gt;&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.raywenderlich.com/124311/asyncdisplaykit-2-0-tutorial-getting-started&quot; target=&quot;_blank&quot;&gt;AsyncDisplayKit 2.0 Tutorial: Getting Started&lt;/a&gt; &lt;strong&gt;&lt;em&gt;[Luke Parham, 5/12/2016]&lt;/em&gt;&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://asyncdisplaykit.org/slack.html&quot; target=&quot;_blank&quot;&gt;Slack do AsyncDisplayKit&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;referências-de-layout&quot;&gt;Referências de Layout&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.raywenderlich.com/124696/asyncdisplaykit-2-0-tutorial-automatic-layout&quot; target=&quot;_blank&quot;&gt;AsyncDisplayKit 2.0 Tutorial: Automatic Layout&lt;/a&gt; &lt;strong&gt;&lt;em&gt;[Luke Parham, 19/12/2016]&lt;/em&gt;&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sqkinHYXTuc&quot; target=&quot;_blank&quot;&gt;Layout at Scale with AsyncDisplayKit 2.0&lt;/a&gt; &lt;strong&gt;&lt;em&gt;[NSMeetup 2016]&lt;/em&gt;&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://huytnguyen.me/froggy-asdk-layout/&quot; target=&quot;_blank&quot;&gt;ASStackLayout Game&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><author><name>“Guga Oliveira“</name></author><category term="UI" /><summary type="html">Sou o Guga Oliveira (@gugaoliveira), empreendedor, cursei engenharia eletrônica mas sempre trabalhei com softwares e programação. Abri uma empresa de desenvolvimento Web em Juiz de Fora no início de 2000, e em 2007 fundamos a Handcom focada em mobilidade. Trabalhamos com iOS desde o início, e criamos aplicativos em sua maioria focados no varejo e com foco empresarial. Em 2014 fundamos a startup Microlocation que foi acelerada pelo Seed-MG e hoje faz parte de nossa solução para o varejo Smart-Retail, atualmente estou estudando Swift e Análise de Dados, e participando bastante do desenvolvimento dos ecossistemas de Minas Gerais com o MGTI em BH e o Zer040 em Juiz de Fora.</summary></entry><entry><title type="html">Adotando Handoff em iOS e macOS</title><link href="http://equinocios.com/continuidade/2017/03/28/adotando-handoff/" rel="alternate" type="text/html" title="Adotando Handoff em iOS e macOS" /><published>2017-03-28T00:00:00+00:00</published><updated>2017-03-28T00:00:00+00:00</updated><id>http://equinocios.com/continuidade/2017/03/28/adotando-handoff</id><content type="html" xml:base="http://equinocios.com/continuidade/2017/03/28/adotando-handoff/">&lt;blockquote&gt;
  &lt;p&gt;Rafael Nobre (&lt;a href=&quot;https://twitter.com/nobre84&quot; target=&quot;_blank&quot;&gt;@nobre84&lt;/a&gt;) é desenvolvedor iOS desde 2009 e trabalha na &lt;a href=&quot;https://prodoctor.net&quot; target=&quot;_blank&quot;&gt;ProDoctor Software&lt;/a&gt;. Odiava o Swift no lançamento, mas foi rapidamente conquistado pela abordagem &lt;em&gt;Swifty&lt;/em&gt; de resolver problemas.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1 id=&quot;continuidade&quot;&gt;Continuidade&lt;/h1&gt;
&lt;p&gt;Handoff faz parte de um conjunto de funcionalidades chamadas coletivamente pela Apple de &lt;strong&gt;Continuidade&lt;/strong&gt;. Seu objetivo é fazer com que diversos dispositivos compatíveis possam se comunicar para que o usuário obtenha mais produtividade ou comodidade. São estes recursos que permitem, por exemplo, atender chamadas recebidas no iPhone pelo Mac, enviar e receber mensagens de texto pelo Messages, desbloquear o Mac pelo Apple Watch ou transferir arquivos via AirDrop, entre outros.&lt;/p&gt;

&lt;h1 id=&quot;handoff&quot;&gt;Handoff&lt;/h1&gt;
&lt;p&gt;A função do Handoff é simples: permitir a continuação de uma &lt;em&gt;atividade&lt;/em&gt; iniciada em um device por outro, desde que esteja &lt;em&gt;próximo&lt;/em&gt; e vinculado à mesma conta iCloud. Essas restrições conferem &lt;em&gt;segurança&lt;/em&gt; e &lt;em&gt;contexto&lt;/em&gt;, impedindo que alguém com acesso físico a um de seus aparelhos possa visualizar ou continuar uma de suas atividades.&lt;/p&gt;

&lt;h2 id=&quot;como-começar&quot;&gt;Como começar&lt;/h2&gt;
&lt;p&gt;Para adotar o Handoff, o primeiro passo é mapear quais &lt;em&gt;atividades&lt;/em&gt; de seu app serão expostas para continuidade, ou seja, identifique funções de alto nível em seu aplicativo cujo estado seria relevante compartilhar com um segundo aparelho de forma transparente. Como exemplos, o Safari permite que uma página visualizada inicialmente no celular seja lida no Mac e vice-versa, assim como o Mail permite que uma mensagem iniciada em um aparelho possa ser alterada e enviada em outro.&lt;/p&gt;

&lt;h2 id=&quot;como-funciona&quot;&gt;Como funciona&lt;/h2&gt;
&lt;p&gt;O &lt;strong&gt;Bluetooth LE&lt;/strong&gt; é um dos elementos chave do Handoff: é ele quem confere ao recurso o fator &lt;em&gt;proximidade&lt;/em&gt;. Quando uma &lt;em&gt;atividade&lt;/em&gt; é declarada pelo desenvolvedor como elegível ao Handoff, é feito um &lt;em&gt;broadcast&lt;/em&gt; pelo sistema para que dispositivos próximos - e conectados à mesma conta do iCloud - possam continuar a atividade atual.&lt;/p&gt;

&lt;p&gt;O interessante é que até este momento, nenhuma informação foi de fato trafegada, apenas o pequeno pacote de &lt;em&gt;advertising&lt;/em&gt; do Bluetooth. Somente quando uma aplicação elegível - isto é, que tenha sido assinada pelo mesmo &lt;em&gt;Team ID&lt;/em&gt; - for acionada pelo usuário para continuar a &lt;em&gt;atividade&lt;/em&gt; é que inicia a transferência de dados, via &lt;em&gt;WiFi&lt;/em&gt;, para o dispositivo de destino.&lt;/p&gt;

&lt;h1 id=&quot;colocando-a-mão-na-massa&quot;&gt;Colocando a mão na massa&lt;/h1&gt;

&lt;h3 id=&quot;primeiro-passo-declarar-atividades&quot;&gt;Primeiro passo: declarar atividades&lt;/h3&gt;
&lt;p&gt;Basta uma entrada no &lt;code class=&quot;highlighter-rouge&quot;&gt;Info.plist&lt;/code&gt; do projeto indicando a lista de tipos que o app sabe lidar (recomenda-se nomenclatura estilo DNS reverso para evitar colisões).&lt;/p&gt;

&lt;div class=&quot;language-xml highlighter-rouge&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;NSUserActivityTypes&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;com.equinocios.Handoff.sample&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;h3 id=&quot;segundo-passo-publicar-uma-atividade&quot;&gt;Segundo passo: publicar uma atividade&lt;/h3&gt;
&lt;p&gt;Agora é preciso encapsular o estado da aplicação em um objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;NSUserActivity&lt;/code&gt;, que será transferido para um segundo app para dar continuidade à tarefa. Este app pode ser macOS, iOS, ou ainda um browser (para ativar este recurso utiliza-se o atributo &lt;code class=&quot;highlighter-rouge&quot;&gt;webpageURL&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;O exemplo abaixo é o &lt;em&gt;bare bones&lt;/em&gt; da implementação em um &lt;code class=&quot;highlighter-rouge&quot;&gt;UIViewController&lt;/code&gt;, no iOS.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;userActivity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUserActivity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;activityType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;com.equinocios.Handoff.sample&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEligibleForHandoff&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;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Novo artigo&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userInfo&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;s&quot;&gt;&quot;user&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;nobre84&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Adotando Handoff em iOS e macOS&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;body&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;# Continuidade&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Handoff faz parte de ...&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;cursorPosition&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;110&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;webpageURL&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;http://equinocios.com/continuidade/2017/03/28/adotando-handoff&quot;&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;userActivity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt; é o principal mecanismo utilizado para trafegar o estado da aplicação. Nele você deverá incluir tudo que for necessário para recriar o estado exato da &lt;em&gt;atividade&lt;/em&gt; do usuário em um dado momento. Um bom candidato para se encarregar disto é o seu &lt;code class=&quot;highlighter-rouge&quot;&gt;view model&lt;/code&gt; ou outra forma de separação de responsabilidades, uma vez que é interessante que o &lt;em&gt;boilerplate&lt;/em&gt; que lida com a criação da &lt;code class=&quot;highlighter-rouge&quot;&gt;NSUserActivity&lt;/code&gt; não conheça o estado de suas &lt;em&gt;views&lt;/em&gt;. Além disso, este não é o único local onde estas informações se farão necessárias, como veremos mais adiante.&lt;/p&gt;

&lt;h3 id=&quot;terceiro-passo-continuar-uma-atividade&quot;&gt;Terceiro passo: continuar uma atividade&lt;/h3&gt;
&lt;p&gt;Para concluir o processo é preciso implementar o método &lt;code class=&quot;highlighter-rouge&quot;&gt;application(_:​continue:​restoration​Handler:​)&lt;/code&gt; no &lt;em&gt;App Delegate&lt;/em&gt; da aplicação macOS ou iOS. É o mesmo método utilizado para receber informações a respeito de buscas utilizando a API de Spotlight ou Intents do Siri.&lt;br /&gt;
Baseado no &lt;code class=&quot;highlighter-rouge&quot;&gt;activityType&lt;/code&gt; da &lt;code class=&quot;highlighter-rouge&quot;&gt;userActivity&lt;/code&gt;, você deve definir a tela a qual seu app será redirecionado, e seu conteúdo através do &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt;. Isto pode ser feito repassando a &lt;code class=&quot;highlighter-rouge&quot;&gt;userActivity&lt;/code&gt; para os &lt;em&gt;childs&lt;/em&gt; desde o &lt;code class=&quot;highlighter-rouge&quot;&gt;rootViewController&lt;/code&gt; usando o método &lt;code class=&quot;highlighter-rouge&quot;&gt;restoreUserActivityState&lt;/code&gt;, sobrescrevendo-o em cada ponto da hierarquia e passando-a adiante, até alcançar o &lt;em&gt;controller&lt;/em&gt; relevante para atualizar seu estado; ou recriar a hierarquia de views do zero para atender o &lt;em&gt;atividade&lt;/em&gt; - o que na minha opinião faz mais sentido.
Para gerenciar este fluxo pode ser utilizado algum mecanismo de roteamento, que desacople do app delegate de forma flexível (e testável!) essa complexa lógica de &lt;strong&gt;qual&lt;/strong&gt; &lt;em&gt;view controller&lt;/em&gt; exibir dado uma &lt;code class=&quot;highlighter-rouge&quot;&gt;NSUserActivity&lt;/code&gt;. Dica: essa lógica pode ser similar à utilizada para definir o &lt;code class=&quot;highlighter-rouge&quot;&gt;rootViewController&lt;/code&gt; da sua &lt;code class=&quot;highlighter-rouge&quot;&gt;Window&lt;/code&gt; no &lt;code class=&quot;highlighter-rouge&quot;&gt;application(_:didFinishLaunchingWithOptions:)&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;application&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;application&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIApplication&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;nv&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUserActivity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;restorationHandler&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;Any&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;o&quot;&gt;-&amp;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;c1&quot;&gt;// Repassando a userActivity, cada um dos controllers na hierarquia deve sobrescrever o método abaixo e empurrando a userActivity para o próximo child&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;window&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;rootViewController&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;restoreUserActivityState&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

	&lt;span class=&quot;c1&quot;&gt;// Ou recriando toda a hierarquia para atender ao Handoff&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;router&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Router&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;activity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;userActivity&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;// Obtém uma pilha de controllers que represente o estado correto do app&lt;/span&gt;
		&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;hierarchy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;router&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;buildHierarchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
		&lt;span class=&quot;c1&quot;&gt;// Substitui o rootViewController da Window e empilha os demais&lt;/span&gt;
		&lt;span class=&quot;n&quot;&gt;router&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;appendHierarchy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;window&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window&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;return&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;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;application&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;application&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIApplication&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;willContinueUserActivityWithType&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userActivityType&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;o&quot;&gt;-&amp;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;c1&quot;&gt;// Sabe-se que irá ocorrer um Handoff, mas o userInfo ainda não foi transmitido.&lt;/span&gt;
	&lt;span class=&quot;c1&quot;&gt;// Pode ser utilizado para exibir feedback ao usuário e/ou exibir um overlay para uma transição suave&lt;/span&gt;
	&lt;span class=&quot;k&quot;&gt;return&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;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;application&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;application&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIApplication&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didFailToContinueUserActivityWithType&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;userActivityType&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;nv&quot;&gt;error&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;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;c1&quot;&gt;// Pode-se exibir feedback de que um problema ocorreu e/ou desfazer um overlay apresentado no willContinueUserActivityWithType&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h1 id=&quot;the-good&quot;&gt;The Good&lt;/h1&gt;
&lt;p&gt;Pronto! Agora nossos apps são capazes de publicar uma atividade e continuá-la em outro device! Isto é realmente incrível, um rápido rascunho pode ser finalizado em um poderoso Mac à noite em casa, assim como um importante e-mail iniciado em casa pode ser enviado no meio do trânsito. A Apple vai te olhar com bons olhos, quem sabe até dê um feature pro seu app! A API é simples, e você já tem praticamente metade do esforço necessário para também adicionar suporte a Spotlight Searching pro seu app ao usar &lt;code class=&quot;highlighter-rouge&quot;&gt;NSUserActivity&lt;/code&gt;’s. Mas, nem tudo são flores!&lt;/p&gt;

&lt;h1 id=&quot;the-bad&quot;&gt;The Bad&lt;/h1&gt;
&lt;p&gt;A API, apesar de simples, possui algumas &lt;em&gt;idiossincrasias&lt;/em&gt;. Lembra do exemplo &lt;em&gt;bare bones&lt;/em&gt; que dei lá em cima? Ele não funciona. Faltaram alguns detalhes importantes, os quais a documentação não é muito clara a respeito. 
O ciclo de vida de uma &lt;code class=&quot;highlighter-rouge&quot;&gt;NSUserActivity&lt;/code&gt; é atrelado a um &lt;code class=&quot;highlighter-rouge&quot;&gt;delegate&lt;/code&gt;, que &lt;em&gt;UIKit/AppKit&lt;/em&gt; já cuidam para nós através de extensões de &lt;code class=&quot;highlighter-rouge&quot;&gt;UIResponder&lt;/code&gt; - o próprio &lt;em&gt;controller&lt;/em&gt;, bastando setar a propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;userActivity&lt;/code&gt; do mesmo.
Ao setar a &lt;code class=&quot;highlighter-rouge&quot;&gt;userActivity&lt;/code&gt; de um &lt;em&gt;controller&lt;/em&gt; no iOS, a mesma está ativa e fazendo &lt;em&gt;broadcast&lt;/em&gt; da &lt;em&gt;atividade&lt;/em&gt;, mesmo que ela não seja mais relevante no seu app (o usuário navegou para outro &lt;em&gt;controller&lt;/em&gt; por exemplo). É necessário então cuidar do ciclo de vida - normalmente acompanhando o do próprio &lt;em&gt;controller&lt;/em&gt;. Já o &lt;em&gt;macOS&lt;/em&gt; faz a coisa certa neste caso.&lt;br /&gt;
Ambas plataformas, porém, proveem uma forma de manter o estado do &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt; de uma &lt;code class=&quot;highlighter-rouge&quot;&gt;NSUserActivity&lt;/code&gt; o mais atualizado possível, através do método &lt;code class=&quot;highlighter-rouge&quot;&gt;updateUserActivityState(_:)&lt;/code&gt;, onde você terá a chance de atualizar o &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt; instantes antes de sua &lt;em&gt;atividade&lt;/em&gt; ser transferida para outro dispositivo ou caso você sete manualmente a flag &lt;code class=&quot;highlighter-rouge&quot;&gt;needsSave&lt;/code&gt; para &lt;code class=&quot;highlighter-rouge&quot;&gt;true&lt;/code&gt;. Plausível, não é mesmo? O inesperado é que, parte da implementação deste método simplesmente &lt;strong&gt;esvazia&lt;/strong&gt; todo o conteúdo do &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt;! Ou seja, se você não fizer &lt;em&gt;override&lt;/em&gt; deste método, nada funciona!&lt;br /&gt;
Existe também uma propriedade chamada &lt;code class=&quot;highlighter-rouge&quot;&gt;requiredUserInfoKeys&lt;/code&gt; que, digamos, indica que tudo que você adicionar ao &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt; e não adicionar aqui, será jogado fora! Astuto, não!? Tem uma pequena nota documentando este comportamento, mas até hoje não consigo ver o sentido. 
Corrigindo então nossa implementação ingênua para algo mais próximo da realidade:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&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;viewDidAppear&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;animated&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;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;viewDidAppear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;animated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;startUserActivity&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;override&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;viewDidDisappear&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;animated&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;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;viewDidDisappear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;animated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;stopUserActivity&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;override&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;updateUserActivityState&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;userActivity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUserActivity&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;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;addUserInfoEntries&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;nf&quot;&gt;uiStateDictionary&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;updateUserActivityState&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userActivity&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;startUserActivity&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;userActivity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUserActivity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;activityType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;com.equinocios.Handoff.sample&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isEligibleForHandoff&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;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Novo artigo&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userInfo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;uiStateDictionary&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;keys&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;userInfo&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;keys&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requiredUserInfoKeys&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Set&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;String&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;keys&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;flatMap&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;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;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;userActivity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;webpageURL&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;http://equinocios.com/continuidade/2017/03/28/adotando-handoff&quot;&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;userActivity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;userActivity&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;stopUserActivity&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;userActivity&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;invalidate&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;userActivity&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;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;uiStateDictionary&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;AnyHashable&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;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;user&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;nobre84&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;title&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Adotando Handoff em iOS e macOS&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;body&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;# Continuidade&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Handoff faz parte de ...&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;cursorPosition&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;110&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;p&gt;Outro aspecto documentado, mas que pode pegá-lo de surpresa, agora ao continuar a &lt;em&gt;atividade&lt;/em&gt;, é que se por algum motivo o seu método &lt;code class=&quot;highlighter-rouge&quot;&gt;application(_:didFinishLaunchingWithOptions:)&lt;/code&gt; retornar &lt;code class=&quot;highlighter-rouge&quot;&gt;false&lt;/code&gt;, o sistema jamais chamará o método &lt;code class=&quot;highlighter-rouge&quot;&gt;application(_:​continue:​restoration​Handler:​)&lt;/code&gt; e você não poderá concluir o processo. Logo, caso você manipule o retorno do primeiro método, terá de identificar se o app foi aberto por conta de uma &lt;em&gt;atividade&lt;/em&gt; inspecionando o dicionário &lt;code class=&quot;highlighter-rouge&quot;&gt;launchOptions&lt;/code&gt; quanto à presença da chave &lt;code class=&quot;highlighter-rouge&quot;&gt;user​Activity​Dictionary&lt;/code&gt;, retornando &lt;code class=&quot;highlighter-rouge&quot;&gt;true&lt;/code&gt; neste caso.&lt;/p&gt;

&lt;h1 id=&quot;the-ugly&quot;&gt;The Ugly&lt;/h1&gt;
&lt;p&gt;O Handoff apresenta em algumas ocasiões falhas que podem te deixar louco. Em muitos casos basta tentar novamente e tudo dá certo, porém não é incomum ter que deslogar e logar novamente no iCloud vezes para corrigir algum problema inexplicável, sobretudo quando se está utilizando versões diferentes do iOS (o recurso está disponível desde o iOS 8).&lt;br /&gt;
Entretanto, a coroa vai pra um bug que pouca ou nenhuma informação encontrei a respeito na Web (&lt;a href=&quot;http://stackoverflow.com/questions/38462031/cant-handoff-from-mac-to-ios-even-though-handoff-from-ios-to-mac-works-fine?noredirect=1#comment72785636_38462031&quot;&gt;1&lt;/a&gt;, &lt;a href=&quot;http://stackoverflow.com/questions/41720356/native-mac-app-fails-to-handoff-to-native-ios-app&quot;&gt;2&lt;/a&gt;, &lt;a href=&quot;https://forums.developer.apple.com/search.jspa?q=handoff&quot;&gt;3&lt;/a&gt;), e que tenho um &lt;em&gt;DTS&lt;/em&gt; da Apple em aberto até hoje (reproduziram o problema mas não possuem solução), é o fato de que (ao menos em ambiente de desenvolvimento) um Handoff iniciado no Mac não aparece em outros dispositivos, enquanto do iOS para iOS ou iOS para Mac funciona normalmente. Nosso colega &lt;a href=&quot;https://twitter.com/reprotector&quot; target=&quot;_blank&quot;&gt;Renan Protector&lt;/a&gt; utiliza Handoff no &lt;a href=&quot;https://getblogo.com&quot; target=&quot;_blank&quot;&gt;Blogo&lt;/a&gt; e segundo ele, em produção tudo funciona. Espero compartilhar da mesma experiência em breve!&lt;/p&gt;

&lt;h1 id=&quot;conclusão&quot;&gt;Conclusão&lt;/h1&gt;
&lt;p&gt;Fora os pequenos grilos, é uma tecnologia muito interessante e útil para se adotar! A experiência do usuário é a privilegiada, mesmo que a custo de alguns cabelos brancos!&lt;br /&gt;
Dúvidas, críticas e sugestões, enviem pelos comentários abaixo, ou diretamente no &lt;a href=&quot;http://iosdevbr.herokuapp.com&quot;&gt;Slack iOS Dev BR&lt;/a&gt; - &lt;code class=&quot;highlighter-rouge&quot;&gt;@nobre84&lt;/code&gt;. Até a próxima!&lt;/p&gt;

&lt;h1 id=&quot;referência-oficial&quot;&gt;Referência oficial:&lt;/h1&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html#//apple_ref/doc/uid/TP40014338-CH3-SW1&quot;&gt;Handoff Programming Guide&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Rafael Nobre</name></author><category term="continuidade" /><summary type="html">Rafael Nobre (@nobre84) é desenvolvedor iOS desde 2009 e trabalha na ProDoctor Software. Odiava o Swift no lançamento, mas foi rapidamente conquistado pela abordagem Swifty de resolver problemas.</summary></entry><entry><title type="html">CoreBluetooth na Prática</title><link href="http://equinocios.com/bluetooth/2017/03/27/corebluetooth-na-pratica/" rel="alternate" type="text/html" title="CoreBluetooth na Prática" /><published>2017-03-27T00:00:00+00:00</published><updated>2017-03-27T00:00:00+00:00</updated><id>http://equinocios.com/bluetooth/2017/03/27/corebluetooth-na-pratica</id><content type="html" xml:base="http://equinocios.com/bluetooth/2017/03/27/corebluetooth-na-pratica/">&lt;blockquote&gt;
  &lt;p&gt;Leonardo Cardoso (&lt;a href=&quot;https://twitter.com/leocardz&quot; target=&quot;_blank&quot;&gt;@leocardz&lt;/a&gt;) começou a trabalhar com mobile desde 2010 com a plataforma do robozinho verde, mas veio para a maçã em 2014, atualmente lidera o time iOS da &lt;a href=&quot;https://1aim.com&quot; target=&quot;_blank&quot;&gt;1aim&lt;/a&gt;, em Berlim. É também um entusiasta open source e desenvolveu alguns projetos que podem ser acessados no seu perfil do &lt;a href=&quot;https://github.com/leonardocardoso&quot; target=&quot;_blank&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1 id=&quot;intro&quot;&gt;Intro&lt;/h1&gt;

&lt;p&gt;É muito comum hoje estarmos em contato com dispositivos sem fio no nosso dia-a-dia. Seja um &lt;em&gt;headphone&lt;/em&gt;, um &lt;em&gt;mouse&lt;/em&gt;, um teclado, ou o famigerado &lt;em&gt;Apple Watch&lt;/em&gt;. A lista é extensa… Todos eles, porém, utilizam basicamente uma mesma tecnologia que os torna de fato &lt;em&gt;wireless&lt;/em&gt;: &lt;strong&gt;Bluetooth®&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Aqui vamos aprender brevemente os papeis executados e propriedades difundidas numa conexão via &lt;em&gt;Bluetooth&lt;/em&gt;, e os modos de execução desses papeis utilizando o &lt;em&gt;framework&lt;/em&gt; &lt;strong&gt;Core Bluetooth&lt;/strong&gt;, que nos dá o suporte à versão 4.0 (&lt;em&gt;a.k.a smart, a.k.a. low-energy&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Primeiramente vamos aos modos de execução.&lt;/p&gt;

&lt;h1 id=&quot;modos-de-execução&quot;&gt;Modos de Execução&lt;/h1&gt;

&lt;p&gt;O &lt;strong&gt;Core Bluetooth&lt;/strong&gt;, ou CB, nos proporciona dois modos de execução, &lt;em&gt;Foreground&lt;/em&gt; e &lt;em&gt;Background&lt;/em&gt;. Assim, podemos definir bem se queremos nossos &lt;em&gt;apps&lt;/em&gt; “conectáveis” apenas quando o usuário estiver interagindo com ele ou não. Alguns aspectos definem bem esses modos, são eles:&lt;/p&gt;

&lt;h2 id=&quot;foreground&quot;&gt;Foreground&lt;/h2&gt;

&lt;p&gt;Se o app é minimizado ou outro app se torna o principal utilizado pelo usuário, nosso suporte &lt;em&gt;Bluetooth&lt;/em&gt; vai junto. Assim, no estado suspenso, seu &lt;em&gt;app&lt;/em&gt; não é capaz de realizar tarefas relacionadas a &lt;em&gt;Bluetooth&lt;/em&gt;, nem fica ciente de eventos relacionados a &lt;em&gt;Bluetooth&lt;/em&gt;. Porém a lista de eventos recebidos enquanto o &lt;em&gt;app&lt;/em&gt; estava em &lt;em&gt;background&lt;/em&gt; é empilhada e esses eventos são entregues quando o usuário resumir o &lt;em&gt;app&lt;/em&gt;, tornando-o ativo novamente.&lt;/p&gt;

&lt;p&gt;Explicaremos mais abaixo a diferença entre os papeis e as propriedades, mas nesse modo caso o aplicativo não esteja ativo, o periférico não consegue enviar propagandas (&lt;em&gt;advertising&lt;/em&gt;) e a central não consegue difundir seu sinal (&lt;em&gt;scanning&lt;/em&gt;), porém a execução de &lt;em&gt;advertising&lt;/em&gt; e &lt;em&gt;scanning&lt;/em&gt; são respondidas sob demanda, praticamente sem atrasos.&lt;/p&gt;

&lt;p&gt;A vantagem de usarmos em &lt;em&gt;Foreground&lt;/em&gt; é que temos o todos os recursos do sistema ao nosso alcance, como por exemplo, atualização de &lt;em&gt;views&lt;/em&gt; e tarefas sem tempo limite de execução. Ainda nesse modo, nossa &lt;em&gt;stack&lt;/em&gt; de dispositivos é bem distrinchada, inclusive tendo a opção de escolher se queremos escanear o mesmo periférico por alguma razão específica. Isso é feito através de uma propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;CBCentralManagerScanOptionAllowDuplicatesKey&lt;/code&gt;, o que no modo &lt;em&gt;Background&lt;/em&gt; é ignorada, assim como outras propriedades são tratadas diferentes quando executadas em modos &lt;em&gt;Foreground&lt;/em&gt; e &lt;em&gt;Background&lt;/em&gt; e elas podem ser achadas nas &lt;a href=&quot;#referncias&quot;&gt;Referências&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;background&quot;&gt;Background&lt;/h2&gt;

&lt;p&gt;Aqui já começamos dizendo que os recursos de sistemas são limitados. Temos também &lt;em&gt;10 segundos&lt;/em&gt; no máximo para executar uma tarefa nesse modo. Mas creio que isso é mais do que suficiente. O intervalo de execução de &lt;em&gt;advertising&lt;/em&gt; e &lt;em&gt;scanning&lt;/em&gt; pode ser mais demorado. Isso é feito em prol de economizar bateria do seu dispositivo. Aqui, eventos do mesmo dispositivo são combinados num único evento com seus &lt;em&gt;serviços e características&lt;/em&gt;, ou seja, a opção de escanear o mesmo dispositivo mais de uma vez é descartada.&lt;/p&gt;

&lt;p&gt;A vantagem desse modo é permitir que nosso &lt;em&gt;app&lt;/em&gt; não precisa estar ativo para trocarmos dados entre centrais e periféricos. Então, só para esclarecer, o sistema acorda nosso &lt;em&gt;app&lt;/em&gt; de um estado suspenso, permitindo ler, escrever, inscrever em características, escutar eventos. Tudo em &lt;em&gt;background&lt;/em&gt;. Mas mesmo que tenhamos permissão de rodar em &lt;em&gt;background&lt;/em&gt;, nosso &lt;em&gt;app&lt;/em&gt; não vai rodar sempre. Isso pode acontecer porque eventualmente o sistema pode finalizar nosso &lt;em&gt;app&lt;/em&gt; para liberar memória para o &lt;em&gt;app&lt;/em&gt; que está no estado ativo. A partir do &lt;em&gt;iOS7&lt;/em&gt;, é permitido salvar os estados dos dispositivos, conexões pendentes, etc., antes de uma interrupção e então restaurá-los depois.&lt;/p&gt;

&lt;p&gt;Como um exemplo para essa restauração de estados, vamos imaginar que você tenha desenvolvido um dispositivo de segurança que se comunica com uma fechadura eletrônica equipada com &lt;em&gt;Bluetooth&lt;/em&gt;. O &lt;em&gt;app&lt;/em&gt; e a fechadura podem interagir para que a fechadura se tranque automaticamente quando o usuário saia da casa e destranque quando o usuário voltar. Tudo isso com o &lt;em&gt;iPhone&lt;/em&gt; no bolso. Quando o usuário sair de casa, o &lt;em&gt;iPhone&lt;/em&gt; pode eventualmente sair do alcance da fechadura e, então, perder conexão. Nesse caso, o usuário pode simplesmente chamar a função para conectar o dispositivo, mesmo não estando no raio de alcance e, assim, a conexão será refeita quando eles estiverem de novo ao alcance. Isso acontece porque a requisição de conexão de dispositivos não expira.&lt;/p&gt;

&lt;p&gt;Agora imagina que o usuário está fora de casa em uma viagem. Se o &lt;em&gt;app&lt;/em&gt; é finalizado pelo sistema enquanto o usuário está fora, o &lt;em&gt;app&lt;/em&gt; não vai ser capaz de se reconectar com a fechadura quando o usuário retornar. Assim, a fechadura não vai destrancar. Para apps como estes, é definitivamente necessário usar a opção de salvamento e restauração de estados.&lt;/p&gt;

&lt;p&gt;Observação: &lt;em&gt;macOS&lt;/em&gt; e &lt;em&gt;iOS&lt;/em&gt; funcionam um pouco diferente nos papeis de periférico e central. Por exemplo, &lt;em&gt;macOS&lt;/em&gt; não aceita a &lt;em&gt;flag&lt;/em&gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;CBCentralManagerOptionRestoreIdentifierKey&lt;/code&gt;, porque o &lt;em&gt;background&lt;/em&gt; do &lt;em&gt;macOS&lt;/em&gt; não finaliza &lt;em&gt;apps&lt;/em&gt; como o &lt;em&gt;iOS&lt;/em&gt; faz, em teoria.&lt;/p&gt;

&lt;p&gt;Para usar o modo &lt;em&gt;Background&lt;/em&gt;, precisamos ainda definir &lt;em&gt;flags&lt;/em&gt; no &lt;code class=&quot;highlighter-rouge&quot;&gt;Info.plist&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;bluetooth-peripheral&lt;/code&gt;: Se quisermos usar um periférico em &lt;em&gt;background&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;bluetooth-central&lt;/code&gt;: Se quisermos usar uma central em &lt;em&gt;background&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Se adicionarmos o suporte via &lt;code class=&quot;highlighter-rouge&quot;&gt;Target &amp;gt; Capabilities &amp;gt; Background Modes&lt;/code&gt;, selecionando &lt;code class=&quot;highlighter-rouge&quot;&gt;Uses Bluetooth LE accessories (central)&lt;/code&gt; e/ou &lt;code class=&quot;highlighter-rouge&quot;&gt;Act as Bluetooth LE accessory (peripheral)&lt;/code&gt;, elas são adicionadas automaticamente no &lt;code class=&quot;highlighter-rouge&quot;&gt;Info.plist&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Importante&lt;/strong&gt;: Não esqueça de adicionar a &lt;em&gt;flag&lt;/em&gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;Privacy - Bluetooth Peripheral Usage Description&lt;/code&gt; para que o usuário permita que esteja utilizando o dispositivo como periférico, assim como fazemos quando queremos utilizar a câmera ou localização.&lt;/p&gt;

&lt;h1 id=&quot;papeis&quot;&gt;Papeis&lt;/h1&gt;

&lt;p&gt;Nesse jogo de conexões &lt;em&gt;Bluetooth&lt;/em&gt;, nós temos dois papeis distintos e bem especificados que funcionam como uma abordagem &lt;strong&gt;Client-Server&lt;/strong&gt;. São eles: &lt;strong&gt;Periférico&lt;/strong&gt; e &lt;strong&gt;Central&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;periférico&quot;&gt;Periférico&lt;/h2&gt;

&lt;p&gt;Um periférico é o dispositivo que compartilha seus dados para a central. Nesse modo, o sistema acorda nosso app para processar tarefas de leitura, escrita, inscrições de eventos vindos da central. É o dispositivo que funciona como &lt;em&gt;Server&lt;/em&gt;, ou seja, tem os dados que se desejam.&lt;/p&gt;

&lt;p&gt;Quando um periférico está sendo executado em &lt;em&gt;Background&lt;/em&gt;, seus serviços são realocados para uma área de “&lt;em&gt;overflow&lt;/em&gt;” especial, ou seja, todos os &lt;em&gt;UUIDs&lt;/em&gt; dos serviços contidos na valor da propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;CBAdvertisementDataServiceUUIDsKey&lt;/code&gt;. Sendo assim, ele só pode ser descoberto por um dispositivo que esteja explicitamente escaneando por ele, procurando por alguma de sua característica, basicamente seu indentificador.&lt;/p&gt;

&lt;h2 id=&quot;central&quot;&gt;Central&lt;/h2&gt;

&lt;p&gt;Uma central é o dispositivo que requer informações de dispositivos periféricos. Nesse caso, ela escaneia, connecta, obtém dados e envia dados, os explora. O &lt;em&gt;Client&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;O sistema acorda nossa central quando eventos de mudança de estado ocorrem com o periférico, tais como conexão estabelecida ou cortada com o periférico, quando periférico atualiza informações de suas caractéristicas, ou ainda quando nossa central está perto de ser finalizada e também restaurada.&lt;/p&gt;

&lt;h3 id=&quot;exemplo&quot;&gt;Exemplo&lt;/h3&gt;

&lt;p&gt;Imagina o funcionamento de um medidor de batimento cardíaco de praticantes de esportes. Nesse caso, o periférico seria o dispositivo medidor que está alocado abaixo do peito do corredor. E um &lt;em&gt;app&lt;/em&gt; no &lt;em&gt;iPhone&lt;/em&gt; poderia ler esse valor e mostrar para o usuário em tempo real, fazendo o &lt;em&gt;iPhone&lt;/em&gt; funcionar como central, numa ação em &lt;em&gt;Foreground&lt;/em&gt;. Agora imagina que o corredor não vai querer ficar olhando para seu &lt;em&gt;iPhone&lt;/em&gt; todo o tempo, então, no modo &lt;em&gt;Background&lt;/em&gt;, o &lt;em&gt;iPhone&lt;/em&gt; captura dados dos batimentos e guarda num &lt;em&gt;log&lt;/em&gt; no qual o usuário pode checar as variações quando terminar seu exercício.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/leonardocardoso/communication.png&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;conexão&quot;&gt;Conexão&lt;/h1&gt;

&lt;p&gt;A conexão entre uma central e um periférico é feita através de escaneamento e propaganda. Basicamente esse é o fluxo:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Um periférico difunde um sinal que pode ser conectado usando pacotes de propaganda;&lt;/li&gt;
  &lt;li&gt;Enquanto a central difunde um sinal que está procurando por periférico;&lt;/li&gt;
  &lt;li&gt;Quando uma central encontra um periférico, ele pode explorar primeiro requisitar a conexão, o que pode ser rejeitada pelo periférico ou não. Essa conexão pode ser encriptada com a encriptação nativa que o &lt;em&gt;Core Bluetooth&lt;/em&gt; nos provê. Se a conexão encriptada for desejada, então um código aparece num dos dispositivos para ser digitado no outro e assim criar pares de criptografia administrados pelo próprio sistema, tornando-os dispositivos confiáveis. Se nenhuma criptografia for requerida, então a conexão é feita automática;&lt;/li&gt;
  &lt;li&gt;Após a conexão ser feita, a central pode então ordenar que o periférico descubra serviços, basicamente a central está explorando os serviços do periférico;&lt;/li&gt;
  &lt;li&gt;Após serviços descobertos, a central pode então ordenar que o periférico descubra características, basicamente a central está explorando as características de cada serviço do periférico;&lt;/li&gt;
  &lt;li&gt;Descobertas as características, a central pode então ler valores das características estaticamente ou se increver naquela característica e caso o periférico atualize o valor dela, a central será notificada com o novo valor.&lt;/li&gt;
  &lt;li&gt;A conexão pode ser finalizada, se for o caso.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/img/leonardocardoso/advertisingdiscovery.png&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;serviços-e-características&quot;&gt;Serviços e Características&lt;/h1&gt;

&lt;p&gt;As trocas de dados feitas por dispositivos conectados são através de propriedades e elas são serviços e características já comentadas em algumas partes anteriormente.&lt;/p&gt;

&lt;p&gt;Um serviço é uma coleção de dados e comportamentos associados para completar uma tarefa ou uma função de um disposito, ou partes de um dispositivo. Esses comportamentos são chamados de características. Uma característica provê mais detalhes sobre um serviço de um periférico. Parece basicamente uma descrição daqueles verbetes que você procura em um dicionário. Uma definição te leva pra outra e você fica num eterno &lt;em&gt;loop&lt;/em&gt;. Mas vamos tentar explicar melhor mais abaixo.&lt;/p&gt;

&lt;p&gt;Serviços podem ter outros serviços relacionados, como dependências, apontando para &lt;em&gt;UUIDs&lt;/em&gt; de outros serviços. Cada característica também tem &lt;em&gt;UUID&lt;/em&gt; que a possa indentificar.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/leonardocardoso/servicescharacterisctics.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Então nesse exemplo nós temos dois sensores que funcionam diferentes um do outro mas juntos eles produzem um serviço, que é o Batimento Cardíaco. Para que ele funcione corretamente, o sensor cardíaco deve estar posicionado no local ideal.&lt;/p&gt;

&lt;p&gt;Ainda utilizando o nosso exemplo anterior, suponha que no dispositivo de batimento cardíaco poderíamos ter dois serviços, um com duas caracterícticas e outro com apenas uma:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Serviço 1: Batimentos Cardíacos
    &lt;ul&gt;
      &lt;li&gt;Característica 1: Medição dos Batimentos Cardíacos&lt;/li&gt;
      &lt;li&gt;Característica 2: Localização Adequada do Dispositivo&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Serviço 2: Status
    &lt;ul&gt;
      &lt;li&gt;Característica 1: Nível de Bateria&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mas um periférico é nada se não estiver enviando propagandas. Um pacote de propaganda é relativamente um pequeno agrupamento de dados que tem informações sobre o que o dispositivo periférico para um reconhecimento inicial. Dados como nome do dispositivo, &lt;em&gt;UUID&lt;/em&gt; e &lt;em&gt;RSSI&lt;/em&gt;, que é uma informação de quão forte é o sinal do periférico.&lt;/p&gt;

&lt;h1 id=&quot;pra-onde-vamos-nós&quot;&gt;Pra onde vamos nós?&lt;/h1&gt;

&lt;p&gt;Nós vamos exemplificar aqui o seguinte:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Papeis
    &lt;ul&gt;
      &lt;li&gt;&lt;em&gt;iOS&lt;/em&gt; como Periférico&lt;/li&gt;
      &lt;li&gt;&lt;em&gt;macOS&lt;/em&gt; como Central&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Modos
    &lt;ul&gt;
      &lt;li&gt;&lt;em&gt;Foreground&lt;/em&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Para conferir o modo &lt;em&gt;background&lt;/em&gt;, confira no &lt;a href=&quot;https://github.com/LeonardoCardoso/BLE{:target=&amp;quot;_blank&amp;quot;}&quot;&gt;repositório desse projeto no GitHub&lt;/a&gt;, no &lt;em&gt;branch&lt;/em&gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;background&lt;/code&gt;.&lt;/p&gt;

&lt;h1 id=&quot;code-snippets&quot;&gt;Code Snippets&lt;/h1&gt;

&lt;p&gt;Devemos primeiro ligar nosso app com o &lt;code class=&quot;highlighter-rouge&quot;&gt;CoreBluetooth&lt;/code&gt;. Então, vá &lt;code class=&quot;highlighter-rouge&quot;&gt;Project&lt;/code&gt; -&amp;gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;Targets&lt;/code&gt; -&amp;gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;Build Phases&lt;/code&gt; -&amp;gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;Link Binary with Libraries&lt;/code&gt; -&amp;gt; Procura por &lt;code class=&quot;highlighter-rouge&quot;&gt;CoreBluetooth.framework&lt;/code&gt; e então o adiciona.&lt;/p&gt;

&lt;h2 id=&quot;foreground-1&quot;&gt;Foreground&lt;/h2&gt;

&lt;p&gt;Primeiro, vamos criar um protocolor para receber os eventos escutados do &lt;code class=&quot;highlighter-rouge&quot;&gt;BluetoothManager&lt;/code&gt; e atualizar as views dos nossos &lt;code class=&quot;highlighter-rouge&quot;&gt;ViewController&lt;/code&gt;s. Vamos chamá-lo de &lt;code class=&quot;highlighter-rouge&quot;&gt;BlueEar&lt;/code&gt;. E tem uma versão para a &lt;code class=&quot;highlighter-rouge&quot;&gt;Central&lt;/code&gt; e outra pro &lt;code class=&quot;highlighter-rouge&quot;&gt;Peripheral&lt;/code&gt;. Assim como o &lt;code class=&quot;highlighter-rouge&quot;&gt;BlueEar&lt;/code&gt;, teremos uma classe que será a administradora da nossa conexão &lt;em&gt;Bluetooth&lt;/em&gt; e é a &lt;code class=&quot;highlighter-rouge&quot;&gt;BluetoothManager&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;ios&quot;&gt;iOS&lt;/h3&gt;

&lt;h4 id=&quot;blueear&quot;&gt;BlueEar&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;kd&quot;&gt;protocol&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;didStartConfiguration&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;didStartAdvertising&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;didSendData&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;didReceiveData&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;h4 id=&quot;bluetoothmanager&quot;&gt;BluetoothManager&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSObject&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Properties&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripheralId&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;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;62443cc7-15bc-4136-bf5d-0ad80c459215&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;serviceUUID&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;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;0cdbe648-eed0-11e6-bc64-92361f002671&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristicUUID&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;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;199ab74c-eed0-11E6-BC64-92361F002672&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;localName&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;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Peripheral - iOS&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;properties&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristicProperties&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read&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;notify&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;writeWithoutResponse&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;write&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;permissions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBAttributePermissions&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;readable&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;writeable&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;bluetoothMessaging&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;peripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&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;serviceCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBMutableService&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;characterisctic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBMutableCharacteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Initializers&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;convenience&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;delegate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;nf&quot;&gt;init&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;bluetoothMessaging&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delegate&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;serviceUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;uuidString&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;serviceUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&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;characteristicUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;uuidString&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;characteristicUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;nsuuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;serviceUUID&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;characteristicCBUUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;nsuuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristicUUID&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;serviceCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&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;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristicCBUUID&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;c1&quot;&gt;// Configuring service&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;service&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBMutableService&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;serviceCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;primary&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;c1&quot;&gt;// Configuring characteristic&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;characterisctic&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBMutableCharacteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;properties&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;properties&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;kc&quot;&gt;nil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;permissions&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;permissions&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;characterisctic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characterisctic&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;c1&quot;&gt;// Add characterisct to service&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;service&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;characteristics&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;characterisctic&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;bluetoothMessaging&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;didStartConfiguration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;// Initiate peripheral and start advertising&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;peripheralManager&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;delegate&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;nv&quot;&gt;queue&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;nv&quot;&gt;options&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;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;h4 id=&quot;cbperipheralmanagerdelegate&quot;&gt;CBPeripheralManagerDelegate&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;c1&quot;&gt;// MARK: - CBPeripheralManagerDelegate&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManagerDelegate&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;peripheralManagerDidUpdateState&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&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;peripheralManagerDidUpdateState&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;n&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&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;poweredOn&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;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBMutableService&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;service&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;peripheralManager&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;removeAllServices&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;peripheralManager&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;add&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;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;peripheralManager&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didAdd&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBService&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didAdd service&quot;&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;advertisingData&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;kt&quot;&gt;CBAdvertisementDataServiceUUIDsKey&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;service&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;uuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;CBAdvertisementDataLocalNameKey&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Peripheral - iOS&quot;&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;peripheralManager&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;stopAdvertising&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;peripheralManager&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;startAdvertising&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;advertisingData&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;peripheralManagerDidStartAdvertising&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;peripheralManagerDidStartAdvertising&quot;&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;bluetoothMessaging&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;didStartAdvertising&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;// Listen to dynamic values&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// Called when CBPeripheral .setNotifyValue(true, for: characteristic) is called from the central&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;peripheralManager&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didSubscribeTo&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didSubscribeTo characteristic&quot;&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;characterisctic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBMutableCharacteristic&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characterisctic&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;do&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;// Writing data to characteristics&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;dict&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;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;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Hello&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Darkness&quot;&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;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&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;PropertyListSerialization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;fromPropertyList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;format&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;binary&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;mi&quot;&gt;0&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;peripheralManager&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;updateValue&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;nv&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characterisctic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;onSubscribedCentrals&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;central&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;bluetoothMessaging&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;didSendData&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;catch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;n&quot;&gt;error&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;c1&quot;&gt;// Read static values&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// Called when CBPeripheral .readValue(for: characteristic) is called from the central&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;peripheralManager&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didReceiveRead&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBATTRequest&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didReceiveRead request&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;uuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characterisctic&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;uuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;request&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;uuid&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;uuid&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;Match characteristic for static reading&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;c1&quot;&gt;// Called when receiving writing from Central.&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;peripheralManager&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didReceiveWrite&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;requests&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;CBATTRequest&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didReceiveWrite requests&quot;&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;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristicCBUUID&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;request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBATTRequest&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requests&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;filter&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;characteristic&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;uuid&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristicCBUUID&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;first&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;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;request&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;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;c1&quot;&gt;// Send response to central if this writing request asks for response [.withResponse]&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;Sending response: Success&quot;&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;peripheralManager&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;respond&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;request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;withResult&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;success&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;Match characteristic for writing&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;do&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;receivedData&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;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;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;PropertyListSerialization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;propertyList&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;value&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;p&quot;&gt;[],&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;format&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;as?&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;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;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;Written value is: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;receivedData&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bluetoothMessaging&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;didReceiveData&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;return&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;catch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;n&quot;&gt;error&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;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;peripheralManager&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didUnsubscribeFrom&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didUnsubscribeFrom characteristic&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;peripheralManager&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;willRestoreState&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;dict&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;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;willRestoreState&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;peripheralManagerIsReady&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toUpdateSubscribers&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralManager&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;peripheralManagerIsReady&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;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h4 id=&quot;viewcontroller&quot;&gt;ViewController&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ViewController&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIViewController&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - IBOutlet&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@IBOutlet&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&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;kt&quot;&gt;UILabel&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Lifecyle&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;preferredStatusBarStyle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UIStatusBarStyle&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;lightContent&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Properties&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;manager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&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;viewDidAppear&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;animated&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;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;viewDidAppear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;animated&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;manager&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;delegate&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;c1&quot;&gt;// MARK: - BlueEar&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ViewController&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;didStartConfiguration&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;label&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;s&quot;&gt;&quot;Start configuration 🎛&quot;&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;didStartAdvertising&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;label&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;s&quot;&gt;&quot;Start advertising 📻&quot;&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;didSendData&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;label&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;s&quot;&gt;&quot;Did send data ⬆️&quot;&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;didReceiveData&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;label&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;s&quot;&gt;&quot;Did received data ⬇️&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;h4 id=&quot;view&quot;&gt;View&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;/img/leonardocardoso/iOS.png&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;notas&quot;&gt;Notas:&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;No nosso exemplo, o Periférico vai começar a fazer propaganda quando iniciar o &lt;code class=&quot;highlighter-rouge&quot;&gt;app&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Você só pode fazer alguma coisa com o periférico quando a função &lt;code class=&quot;highlighter-rouge&quot;&gt;peripheralManagerDidUpdateState(: CBPeripheralManager)&lt;/code&gt; for chamada e o estado do periférico estiver &lt;code class=&quot;highlighter-rouge&quot;&gt;.poweredOn&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Leituras de valores dinâmicos pela Central usando a função &lt;code class=&quot;highlighter-rouge&quot;&gt;.setNotifyValue(true, for: characteristic)&lt;/code&gt; disparam a função &lt;code class=&quot;highlighter-rouge&quot;&gt;peripheralManager(_: CBPeripheralManager, : CBCentral, : CBCharacteristic)&lt;/code&gt; do periférico, já leituras de valores estáticos usando a função &lt;code class=&quot;highlighter-rouge&quot;&gt;.readValue(for: characteristic)&lt;/code&gt; pela Central, disparam &lt;code class=&quot;highlighter-rouge&quot;&gt;peripheralManager(_: CBPeripheralManager, :CBATTRequest)&lt;/code&gt; do periférico.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;macos&quot;&gt;macOS&lt;/h3&gt;

&lt;h4 id=&quot;blueear-1&quot;&gt;BlueEar&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;kd&quot;&gt;protocol&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;didStartConfiguration&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;didStartScanningPeripherals&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;didConnectPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&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;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didDisconnectPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&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;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didSendData&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;didReceiveData&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;didFailConnection&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;h4 id=&quot;bluetoothmanager-1&quot;&gt;BluetoothManager&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSObject&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Properties&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;serviceUUID&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;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;0cdbe648-eed0-11e6-bc64-92361f002671&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristicUUID&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;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;199ab74c-eed0-11e6-bc64-92361f002672&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;serviceCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;blueEar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;centralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&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;discoveredPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Initializers&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;convenience&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;delegate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;nf&quot;&gt;init&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;blueEar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delegate&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;serviceUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;uuidString&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;serviceUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&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;characteristicUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;uuidString&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;characteristicUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UUID&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;nsuuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;serviceUUID&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;characteristicCBUUID&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;nsuuid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristicUUID&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;// MARK: - Functions&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scan&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;centralManager&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;delegate&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;nv&quot;&gt;queue&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;nv&quot;&gt;options&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blueEar&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;didStartConfiguration&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;h4 id=&quot;cbcentralmanagerdelegate&quot;&gt;CBCentralManagerDelegate&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;c1&quot;&gt;// MARK: - CBCentralManagerDelegate&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManagerDelegate&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;centralManagerDidUpdateState&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;centralManagerDidUpdateState &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&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;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;central&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&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;poweredOn&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;serviceCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blueEar&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;didStartScanningPeripherals&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;centralManager&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;scanForPeripherals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;withServices&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;serviceCBUUID&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;kc&quot;&gt;nil&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;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didDiscover&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;advertisementData&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;n&quot;&gt;rssi&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;RSSI&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSNumber&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;// We must keep a reference to the new discovered peripheral, which means we must retain it.&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;discoveredPeripheral&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;peripheral&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didDiscover:&quot;&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;discoveredPeripheral&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;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&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;discoveredPeripheral&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;delegate&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;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;discoveredPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discoveredPeripheral&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centralManager&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;connect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discoveredPeripheral&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;kc&quot;&gt;nil&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;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didConnect&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didConnect&quot;&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;discoveredPeripheral&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;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&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;blueEar&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;didConnectPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&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;serviceCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discoveredPeripheral&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;discoverServices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&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;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;willRestoreState&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;dict&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;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;willRestoreState&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;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didRetrievePeripherals&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripherals&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;CBPeripheral&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didRetrievePeripherals&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;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didFailToConnect&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didFailToConnect&quot;&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;blueEar&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;didFailConnection&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;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didRetrieveConnectedPeripherals&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripherals&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;CBPeripheral&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didRetrieveConnectedPeripherals&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;centralManager&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;central&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCentralManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didDisconnectPeripheral&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didDisconnectPeripheral&quot;&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;discoveredPeripheral&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;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&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;blueEar&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;didDisconnectPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&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;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h4 id=&quot;cbperipheraldelegate&quot;&gt;CBPeripheralDelegate&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;c1&quot;&gt;// MARK: - CBPeripheralDelegate&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheralDelegate&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didDiscoverServices&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didDiscoverServices&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;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBService&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discoveredPeripheral&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;services&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;filter&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;uuid&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;serviceCBUUID&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;first&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;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBUUID&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristicCBUUID&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;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discoveredPeripheral&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;discoverCharacteristics&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristicCBUUID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;for&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;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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didWriteValueFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didWriteValueFor &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&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;c1&quot;&gt;// After we write data on peripheral, we disconnect it.&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;centralManager&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;cancelPeripheralConnection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;// We stop scanning.&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;centralManager&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;stopScan&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didDiscoverCharacteristicsFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBService&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didDiscoverCharacteristicsFor&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;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristics&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;filter&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;uuid&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;characteristicCBUUID&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;first&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;Matching characteristic&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;// To listen and read dynamic values&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;discoveredPeripheral&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;setNotifyValue&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;nv&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;// To read static values&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// self.discoveredPeripheral?.readValue(for: characteristic)&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didUpdateValueFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didUpdateValueFor&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;// We read&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;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristic&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;do&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;receivedData&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;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;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;PropertyListSerialization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;propertyList&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;value&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;p&quot;&gt;[],&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;format&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;as!&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;String&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;Value read is: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;receivedData&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blueEar&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;didReceiveData&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;catch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;n&quot;&gt;error&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;c1&quot;&gt;// We write&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;do&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Writing on peripheral.&quot;&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;dict&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;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;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Yo&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Lo&quot;&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;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&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;PropertyListSerialization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;fromPropertyList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;format&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;binary&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;mi&quot;&gt;0&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;discoveredPeripheral&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;writeValue&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;nv&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;type&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;withResponse&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;blueEar&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;didSendData&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;catch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;n&quot;&gt;error&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;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;peripheralDidUpdateRSSI&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;peripheralDidUpdateRSSI&quot;&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discoveredPeripheral&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;rssi&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&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;peripheralDidUpdateName&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;peripheralDidUpdateName&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didWriteValueFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;descriptor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBDescriptor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didWriteValueFor&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didModifyServices&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;invalidatedServices&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;CBService&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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didModifyServices&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didUpdateValueFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;descriptor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBDescriptor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didUpdateValueFor&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didDiscoverIncludedServicesFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;service&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBService&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didDiscoverIncludedServicesFor&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didDiscoverDescriptorsFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didDiscoverDescriptorsFor&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;peripheral&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;peripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;didUpdateNotificationStateFor&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;characteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CBCharacteristic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;error&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;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;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;didUpdateNotificationStateFor&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;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h4 id=&quot;viewcontroller-1&quot;&gt;ViewController&lt;/h4&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;Cocoa&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ViewController&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSViewController&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - IBOutlet&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@IBOutlet&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;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSTextField&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@IBOutlet&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;button&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSButton&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Properties&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;manager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: - Lifecyle&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@IBAction&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discover&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;sender&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;manager&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BluetoothManager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;delegate&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;manager&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;scan&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;c1&quot;&gt;// MARK: - BlueEar&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ViewController&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BlueEar&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;didStartConfiguration&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;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Start configuration 🎛&quot;&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;didStartScanningPeripherals&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;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Start scanning peripherals 👀&quot;&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;didConnectPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Did connect to: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&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;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didDisconnectPeripheral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&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;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Did disconnect: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;??&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&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;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;didSendData&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;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Did send data ⬆️&quot;&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;didReceiveData&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;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Did received data ⬇️&quot;&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;didFailConnection&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;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Connection failed 🤷🏽‍♂️&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;h4 id=&quot;view-1&quot;&gt;View&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;/img/leonardocardoso/macOS.png&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;notas-1&quot;&gt;Notas:&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;No nosso exemplo, a Central vai começar a escanear por periféricos quando clicarmor num botão chamado &lt;code class=&quot;highlighter-rouge&quot;&gt;Tap&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Você só pode fazer alguma coisa com a central quando a função &lt;code class=&quot;highlighter-rouge&quot;&gt;centralManagerDidUpdateState(: CBCentralManager)&lt;/code&gt; for chamada e o estado do periférico estiver &lt;code class=&quot;highlighter-rouge&quot;&gt;.poweredOn&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Note que o &lt;code class=&quot;highlighter-rouge&quot;&gt;CBPeripheralDelegate&lt;/code&gt; é diferente do &lt;code class=&quot;highlighter-rouge&quot;&gt;CBPeripheralManagerDelegate&lt;/code&gt; usado no periférico. Ambos são relacionados ao periférico, porém o &lt;code class=&quot;highlighter-rouge&quot;&gt;CBPeripheralDelegate&lt;/code&gt; permite que a central escute eventos sobre o periférico.&lt;/li&gt;
  &lt;li&gt;Ao optar por ler resultados dinâmicos, a central se inscreve em características do periférico, assim sendo alertada por meio de notificações se o periférico alterar seu valor no qual ela esteja inscrita.&lt;/li&gt;
  &lt;li&gt;Quando a central descobre um periférico, devemos manter uma referência para ele, ou seja, devemos retê-lo fazendo com que uma variável dentro do nosso código o receba.&lt;/li&gt;
  &lt;li&gt;Os dados são trasmitidos em formato de &lt;code class=&quot;highlighter-rouge&quot;&gt;Data&lt;/code&gt;, então você deve transformar o que quer transmitir neste tipo de dados para poder ser recebido corretamente no outro lado.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;resultado&quot;&gt;Resultado&lt;/h3&gt;

&lt;p&gt;Na imagem, temos o respectivo: &lt;em&gt;Log&lt;/em&gt; do periférico, &lt;em&gt;iOS&lt;/em&gt;, &lt;em&gt;macOS&lt;/em&gt;, &lt;em&gt;Log&lt;/em&gt; da central.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/img/leonardocardoso/result.mp4&quot; alt=&quot;Click to see a video smoother than this GIF&quot; target=&quot;_blank&quot;&gt;
&lt;img src=&quot;/img/leonardocardoso/result.gif&quot; /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;referências&quot;&gt;Referências&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/AboutCoreBluetooth/Introduction.html&quot; target=&quot;_blank&quot;&gt;CoreBlueetooth&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;agradecimentos&quot;&gt;Agradecimentos&lt;/h3&gt;

&lt;p&gt;Um agradecimento pra galera do &lt;a href=&quot;http://iosdevbr.slack.com&quot; target=&quot;_blank&quot;&gt;Slack iOS Devs BR&lt;/a&gt; pela oportunidade.&lt;/p&gt;

&lt;p&gt;Um abraço, e até próxima.&lt;/p&gt;

&lt;p&gt;Leo&lt;/p&gt;</content><author><name>Leonardo Cardoso</name></author><category term="bluetooth" /><summary type="html">Leonardo Cardoso (@leocardz) começou a trabalhar com mobile desde 2010 com a plataforma do robozinho verde, mas veio para a maçã em 2014, atualmente lidera o time iOS da 1aim, em Berlim. É também um entusiasta open source e desenvolveu alguns projetos que podem ser acessados no seu perfil do GitHub. Intro É muito comum hoje estarmos em contato com dispositivos sem fio no nosso dia-a-dia. Seja um headphone, um mouse, um teclado, ou o famigerado Apple Watch. A lista é extensa… Todos eles, porém, utilizam basicamente uma mesma tecnologia que os torna de fato wireless: Bluetooth®. Aqui vamos aprender brevemente os papeis executados e propriedades difundidas numa conexão via Bluetooth, e os modos de execução desses papeis utilizando o framework Core Bluetooth, que nos dá o suporte à versão 4.0 (a.k.a smart, a.k.a. low-energy). Primeiramente vamos aos modos de execução. Modos de Execução O Core Bluetooth, ou CB, nos proporciona dois modos de execução, Foreground e Background. Assim, podemos definir bem se queremos nossos apps “conectáveis” apenas quando o usuário estiver interagindo com ele ou não. Alguns aspectos definem bem esses modos, são eles: Foreground Se o app é minimizado ou outro app se torna o principal utilizado pelo usuário, nosso suporte Bluetooth vai junto. Assim, no estado suspenso, seu app não é capaz de realizar tarefas relacionadas a Bluetooth, nem fica ciente de eventos relacionados a Bluetooth. Porém a lista de eventos recebidos enquanto o app estava em background é empilhada e esses eventos são entregues quando o usuário resumir o app, tornando-o ativo novamente. Explicaremos mais abaixo a diferença entre os papeis e as propriedades, mas nesse modo caso o aplicativo não esteja ativo, o periférico não consegue enviar propagandas (advertising) e a central não consegue difundir seu sinal (scanning), porém a execução de advertising e scanning são respondidas sob demanda, praticamente sem atrasos. A vantagem de usarmos em Foreground é que temos o todos os recursos do sistema ao nosso alcance, como por exemplo, atualização de views e tarefas sem tempo limite de execução. Ainda nesse modo, nossa stack de dispositivos é bem distrinchada, inclusive tendo a opção de escolher se queremos escanear o mesmo periférico por alguma razão específica. Isso é feito através de uma propriedade CBCentralManagerScanOptionAllowDuplicatesKey, o que no modo Background é ignorada, assim como outras propriedades são tratadas diferentes quando executadas em modos Foreground e Background e elas podem ser achadas nas Referências. Background Aqui já começamos dizendo que os recursos de sistemas são limitados. Temos também 10 segundos no máximo para executar uma tarefa nesse modo. Mas creio que isso é mais do que suficiente. O intervalo de execução de advertising e scanning pode ser mais demorado. Isso é feito em prol de economizar bateria do seu dispositivo. Aqui, eventos do mesmo dispositivo são combinados num único evento com seus serviços e características, ou seja, a opção de escanear o mesmo dispositivo mais de uma vez é descartada. A vantagem desse modo é permitir que nosso app não precisa estar ativo para trocarmos dados entre centrais e periféricos. Então, só para esclarecer, o sistema acorda nosso app de um estado suspenso, permitindo ler, escrever, inscrever em características, escutar eventos. Tudo em background. Mas mesmo que tenhamos permissão de rodar em background, nosso app não vai rodar sempre. Isso pode acontecer porque eventualmente o sistema pode finalizar nosso app para liberar memória para o app que está no estado ativo. A partir do iOS7, é permitido salvar os estados dos dispositivos, conexões pendentes, etc., antes de uma interrupção e então restaurá-los depois. Como um exemplo para essa restauração de estados, vamos imaginar que você tenha desenvolvido um dispositivo de segurança que se comunica com uma fechadura eletrônica equipada com Bluetooth. O app e a fechadura podem interagir para que a fechadura se tranque automaticamente quando o usuário saia da casa e destranque quando o usuário voltar. Tudo isso com o iPhone no bolso. Quando o usuário sair de casa, o iPhone pode eventualmente sair do alcance da fechadura e, então, perder conexão. Nesse caso, o usuário pode simplesmente chamar a função para conectar o dispositivo, mesmo não estando no raio de alcance e, assim, a conexão será refeita quando eles estiverem de novo ao alcance. Isso acontece porque a requisição de conexão de dispositivos não expira. Agora imagina que o usuário está fora de casa em uma viagem. Se o app é finalizado pelo sistema enquanto o usuário está fora, o app não vai ser capaz de se reconectar com a fechadura quando o usuário retornar. Assim, a fechadura não vai destrancar. Para apps como estes, é definitivamente necessário usar a opção de salvamento e restauração de estados. Observação: macOS e iOS funcionam um pouco diferente nos papeis de periférico e central. Por exemplo, macOS não aceita a flag CBCentralManagerOptionRestoreIdentifierKey, porque o background do macOS não finaliza apps como o iOS faz, em teoria. Para usar o modo Background, precisamos ainda definir flags no Info.plist. bluetooth-peripheral: Se quisermos usar um periférico em background bluetooth-central: Se quisermos usar uma central em background Se adicionarmos o suporte via Target &amp;gt; Capabilities &amp;gt; Background Modes, selecionando Uses Bluetooth LE accessories (central) e/ou Act as Bluetooth LE accessory (peripheral), elas são adicionadas automaticamente no Info.plist. Importante: Não esqueça de adicionar a flag Privacy - Bluetooth Peripheral Usage Description para que o usuário permita que esteja utilizando o dispositivo como periférico, assim como fazemos quando queremos utilizar a câmera ou localização. Papeis Nesse jogo de conexões Bluetooth, nós temos dois papeis distintos e bem especificados que funcionam como uma abordagem Client-Server. São eles: Periférico e Central. Periférico Um periférico é o dispositivo que compartilha seus dados para a central. Nesse modo, o sistema acorda nosso app para processar tarefas de leitura, escrita, inscrições de eventos vindos da central. É o dispositivo que funciona como Server, ou seja, tem os dados que se desejam. Quando um periférico está sendo executado em Background, seus serviços são realocados para uma área de “overflow” especial, ou seja, todos os UUIDs dos serviços contidos na valor da propriedade CBAdvertisementDataServiceUUIDsKey. Sendo assim, ele só pode ser descoberto por um dispositivo que esteja explicitamente escaneando por ele, procurando por alguma de sua característica, basicamente seu indentificador. Central Uma central é o dispositivo que requer informações de dispositivos periféricos. Nesse caso, ela escaneia, connecta, obtém dados e envia dados, os explora. O Client. O sistema acorda nossa central quando eventos de mudança de estado ocorrem com o periférico, tais como conexão estabelecida ou cortada com o periférico, quando periférico atualiza informações de suas caractéristicas, ou ainda quando nossa central está perto de ser finalizada e também restaurada. Exemplo Imagina o funcionamento de um medidor de batimento cardíaco de praticantes de esportes. Nesse caso, o periférico seria o dispositivo medidor que está alocado abaixo do peito do corredor. E um app no iPhone poderia ler esse valor e mostrar para o usuário em tempo real, fazendo o iPhone funcionar como central, numa ação em Foreground. Agora imagina que o corredor não vai querer ficar olhando para seu iPhone todo o tempo, então, no modo Background, o iPhone captura dados dos batimentos e guarda num log no qual o usuário pode checar as variações quando terminar seu exercício. Conexão A conexão entre uma central e um periférico é feita através de escaneamento e propaganda. Basicamente esse é o fluxo: Um periférico difunde um sinal que pode ser conectado usando pacotes de propaganda; Enquanto a central difunde um sinal que está procurando por periférico; Quando uma central encontra um periférico, ele pode explorar primeiro requisitar a conexão, o que pode ser rejeitada pelo periférico ou não. Essa conexão pode ser encriptada com a encriptação nativa que o Core Bluetooth nos provê. Se a conexão encriptada for desejada, então um código aparece num dos dispositivos para ser digitado no outro e assim criar pares de criptografia administrados pelo próprio sistema, tornando-os dispositivos confiáveis. Se nenhuma criptografia for requerida, então a conexão é feita automática; Após a conexão ser feita, a central pode então ordenar que o periférico descubra serviços, basicamente a central está explorando os serviços do periférico; Após serviços descobertos, a central pode então ordenar que o periférico descubra características, basicamente a central está explorando as características de cada serviço do periférico; Descobertas as características, a central pode então ler valores das características estaticamente ou se increver naquela característica e caso o periférico atualize o valor dela, a central será notificada com o novo valor. A conexão pode ser finalizada, se for o caso. Serviços e Características As trocas de dados feitas por dispositivos conectados são através de propriedades e elas são serviços e características já comentadas em algumas partes anteriormente. Um serviço é uma coleção de dados e comportamentos associados para completar uma tarefa ou uma função de um disposito, ou partes de um dispositivo. Esses comportamentos são chamados de características. Uma característica provê mais detalhes sobre um serviço de um periférico. Parece basicamente uma descrição daqueles verbetes que você procura em um dicionário. Uma definição te leva pra outra e você fica num eterno loop. Mas vamos tentar explicar melhor mais abaixo. Serviços podem ter outros serviços relacionados, como dependências, apontando para UUIDs de outros serviços. Cada característica também tem UUID que a possa indentificar. Então nesse exemplo nós temos dois sensores que funcionam diferentes um do outro mas juntos eles produzem um serviço, que é o Batimento Cardíaco. Para que ele funcione corretamente, o sensor cardíaco deve estar posicionado no local ideal. Ainda utilizando o nosso exemplo anterior, suponha que no dispositivo de batimento cardíaco poderíamos ter dois serviços, um com duas caracterícticas e outro com apenas uma: Serviço 1: Batimentos Cardíacos Característica 1: Medição dos Batimentos Cardíacos Característica 2: Localização Adequada do Dispositivo Serviço 2: Status Característica 1: Nível de Bateria Mas um periférico é nada se não estiver enviando propagandas. Um pacote de propaganda é relativamente um pequeno agrupamento de dados que tem informações sobre o que o dispositivo periférico para um reconhecimento inicial. Dados como nome do dispositivo, UUID e RSSI, que é uma informação de quão forte é o sinal do periférico. Pra onde vamos nós? Nós vamos exemplificar aqui o seguinte: Papeis iOS como Periférico macOS como Central Modos Foreground Para conferir o modo background, confira no repositório desse projeto no GitHub, no branch background. Code Snippets Devemos primeiro ligar nosso app com o CoreBluetooth. Então, vá Project -&amp;gt; Targets -&amp;gt; Build Phases -&amp;gt; Link Binary with Libraries -&amp;gt; Procura por CoreBluetooth.framework e então o adiciona. Foreground Primeiro, vamos criar um protocolor para receber os eventos escutados do BluetoothManager e atualizar as views dos nossos ViewControllers. Vamos chamá-lo de BlueEar. E tem uma versão para a Central e outra pro Peripheral. Assim como o BlueEar, teremos uma classe que será a administradora da nossa conexão Bluetooth e é a BluetoothManager. iOS BlueEar protocol BlueEar { func didStartConfiguration() func didStartAdvertising() func didSendData() func didReceiveData() } BluetoothManager class BluetoothManager: NSObject { // MARK: - Properties let peripheralId: String = &quot;62443cc7-15bc-4136-bf5d-0ad80c459215&quot; let serviceUUID: String = &quot;0cdbe648-eed0-11e6-bc64-92361f002671&quot; let characteristicUUID: String = &quot;199ab74c-eed0-11E6-BC64-92361F002672&quot; let localName: String = &quot;Peripheral - iOS&quot; let properties: CBCharacteristicProperties = [.read, .notify, .writeWithoutResponse, .write] let permissions: CBAttributePermissions = [.readable, .writeable] var bluetoothMessaging: BlueEar? var peripheralManager: CBPeripheralManager? var serviceCBUUID: CBUUID? var characteristicCBUUID: CBUUID? var service: CBMutableService? var characterisctic: CBMutableCharacteristic? // MARK: - Initializers convenience init (delegate: BlueEar?) { self.init() self.bluetoothMessaging = delegate guard let serviceUUID: UUID = NSUUID(uuidString: self.serviceUUID) as UUID?, let characteristicUUID: UUID = NSUUID(uuidString: self.characteristicUUID) as UUID? else { return } self.serviceCBUUID = CBUUID(nsuuid: serviceUUID) self.characteristicCBUUID = CBUUID(nsuuid: characteristicUUID) guard let serviceCBUUID: CBUUID = self.serviceCBUUID, let characteristicCBUUID: CBUUID = self.characteristicCBUUID else { return } // Configuring service self.service = CBMutableService(type: serviceCBUUID, primary: true) // Configuring characteristic self.characterisctic = CBMutableCharacteristic(type: characteristicCBUUID, properties: self.properties, value: nil, permissions: self.permissions) guard let characterisctic: CBCharacteristic = self.characterisctic else { return } // Add characterisct to service self.service?.characteristics = [characterisctic] self.bluetoothMessaging?.didStartConfiguration() // Initiate peripheral and start advertising self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) } } CBPeripheralManagerDelegate // MARK: - CBPeripheralManagerDelegate extension BluetoothManager: CBPeripheralManagerDelegate { func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { print(&quot;peripheralManagerDidUpdateState&quot;) if peripheral.state == .poweredOn { guard let service: CBMutableService = self.service else { return } self.peripheralManager?.removeAllServices() self.peripheralManager?.add(service) } } func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) { print(&quot;\ndidAdd service&quot;) let advertisingData: [String: Any] = [ CBAdvertisementDataServiceUUIDsKey: [self.service?.uuid], CBAdvertisementDataLocalNameKey: &quot;Peripheral - iOS&quot; ] self.peripheralManager?.stopAdvertising() self.peripheralManager?.startAdvertising(advertisingData) } func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { print(&quot;peripheralManagerDidStartAdvertising&quot;) self.bluetoothMessaging?.didStartAdvertising() } // Listen to dynamic values // Called when CBPeripheral .setNotifyValue(true, for: characteristic) is called from the central func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { print(&quot;\ndidSubscribeTo characteristic&quot;) guard let characterisctic: CBMutableCharacteristic = self.characterisctic else { return } do { // Writing data to characteristics let dict: [String: String] = [&quot;Hello&quot;: &quot;Darkness&quot;] let data: Data = try PropertyListSerialization.data(fromPropertyList: dict, format: .binary, options: 0) self.peripheralManager?.updateValue(data, for: characterisctic, onSubscribedCentrals: [central]) self.bluetoothMessaging?.didSendData() } catch let error { print(error) } } // Read static values // Called when CBPeripheral .readValue(for: characteristic) is called from the central func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { print(&quot;\ndidReceiveRead request&quot;) if let uuid: CBUUID = self.characterisctic?.uuid, request.characteristic.uuid == uuid { print(&quot;Match characteristic for static reading&quot;) } } // Called when receiving writing from Central. func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { print(&quot;\ndidReceiveWrite requests&quot;) guard let characteristicCBUUID: CBUUID = self.characteristicCBUUID, let request: CBATTRequest = requests.filter({ $0.characteristic.uuid == characteristicCBUUID }).first, let value: Data = request.value else { return } // Send response to central if this writing request asks for response [.withResponse] print(&quot;Sending response: Success&quot;) self.peripheralManager?.respond(to: request, withResult: .success) print(&quot;Match characteristic for writing&quot;) do { if let receivedData: [String : String] = try PropertyListSerialization.propertyList(from: value, options: [], format: nil) as? [String: String] { print(&quot;Written value is: \(receivedData)&quot;) self.bluetoothMessaging?.didReceiveData() } else { return } } catch let error { print(error) } } func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { print(&quot;\ndidUnsubscribeFrom characteristic&quot;) } func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String : Any]) { print(&quot;willRestoreState&quot;) } func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) { print(&quot;peripheralManagerIsReady&quot;) } } ViewController import UIKit class ViewController: UIViewController { // MARK: - IBOutlet @IBOutlet var label: UILabel! // MARK: - Lifecyle override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - Properties var manager: BluetoothManager? override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.manager = BluetoothManager(delegate: self) } } // MARK: - BlueEar extension ViewController: BlueEar { func didStartConfiguration() { self.label.text = &quot;Start configuration 🎛&quot; } func didStartAdvertising() { self.label.text = &quot;Start advertising 📻&quot; } func didSendData() { self.label.text = &quot;Did send data ⬆️&quot; } func didReceiveData() { self.label.text = &quot;Did received data ⬇️&quot; } } View Notas: No nosso exemplo, o Periférico vai começar a fazer propaganda quando iniciar o app. Você só pode fazer alguma coisa com o periférico quando a função peripheralManagerDidUpdateState(: CBPeripheralManager) for chamada e o estado do periférico estiver .poweredOn. Leituras de valores dinâmicos pela Central usando a função .setNotifyValue(true, for: characteristic) disparam a função peripheralManager(_: CBPeripheralManager, : CBCentral, : CBCharacteristic) do periférico, já leituras de valores estáticos usando a função .readValue(for: characteristic) pela Central, disparam peripheralManager(_: CBPeripheralManager, :CBATTRequest) do periférico. macOS BlueEar protocol BlueEar { func didStartConfiguration() func didStartScanningPeripherals() func didConnectPeripheral(name: String?) func didDisconnectPeripheral(name: String?) func didSendData() func didReceiveData() func didFailConnection() } BluetoothManager class BluetoothManager: NSObject { // MARK: - Properties let serviceUUID: String = &quot;0cdbe648-eed0-11e6-bc64-92361f002671&quot; let characteristicUUID: String = &quot;199ab74c-eed0-11e6-bc64-92361f002672&quot; var serviceCBUUID: CBUUID? var characteristicCBUUID: CBUUID? var blueEar: BlueEar? var centralManager: CBCentralManager? var discoveredPeripheral: CBPeripheral? // MARK: - Initializers convenience init (delegate: BlueEar) { self.init() self.blueEar = delegate guard let serviceUUID: UUID = NSUUID(uuidString: self.serviceUUID) as UUID?, let characteristicUUID: UUID = NSUUID(uuidString: self.characteristicUUID) as UUID? else { return } self.serviceCBUUID = CBUUID(nsuuid: serviceUUID) self.characteristicCBUUID = CBUUID(nsuuid: characteristicUUID) } // MARK: - Functions func scan() { self.centralManager = CBCentralManager(delegate: self, queue: nil, options: nil) self.blueEar?.didStartConfiguration() } } CBCentralManagerDelegate // MARK: - CBCentralManagerDelegate extension BluetoothManager: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { print(&quot;\ncentralManagerDidUpdateState \(Date())&quot;) if central.state == .poweredOn { guard let serviceCBUUID: CBUUID = self.serviceCBUUID else { return } self.blueEar?.didStartScanningPeripherals() self.centralManager?.scanForPeripherals(withServices: [serviceCBUUID], options: nil) } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // We must keep a reference to the new discovered peripheral, which means we must retain it. self.discoveredPeripheral = peripheral print(&quot;\ndidDiscover:&quot;, self.discoveredPeripheral?.name ?? &quot;&quot;) self.discoveredPeripheral?.delegate = self guard let discoveredPeripheral: CBPeripheral = self.discoveredPeripheral else { return } self.centralManager?.connect(discoveredPeripheral, options: nil) } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print(&quot;\ndidConnect&quot;, self.discoveredPeripheral?.name ?? &quot;&quot;) self.blueEar?.didConnectPeripheral(name: peripheral.name ?? &quot;&quot;) guard let serviceCBUUID: CBUUID = self.serviceCBUUID else { return } self.discoveredPeripheral?.discoverServices([serviceCBUUID]) } func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { print(&quot;willRestoreState&quot;) } func centralManager(_ central: CBCentralManager, didRetrievePeripherals peripherals: [CBPeripheral]) { print(&quot;\ndidRetrievePeripherals&quot;) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { print(&quot;\ndidFailToConnect&quot;) self.blueEar?.didFailConnection() } func centralManager(_ central: CBCentralManager, didRetrieveConnectedPeripherals peripherals: [CBPeripheral]) { print(&quot;\ndidRetrieveConnectedPeripherals&quot;) } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { print(&quot;\ndidDisconnectPeripheral&quot;, self.discoveredPeripheral?.name ?? &quot;&quot;) self.blueEar?.didDisconnectPeripheral(name: peripheral.name ?? &quot;&quot;) } } CBPeripheralDelegate // MARK: - CBPeripheralDelegate extension BluetoothManager: CBPeripheralDelegate { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { print(&quot;\ndidDiscoverServices&quot;) if let service: CBService = self.discoveredPeripheral?.services?.filter({ $0.uuid == self.serviceCBUUID }).first { guard let characteristicCBUUID: CBUUID = self.characteristicCBUUID else { return } self.discoveredPeripheral?.discoverCharacteristics([characteristicCBUUID], for: service) } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { print(&quot;\ndidWriteValueFor \(Date())&quot;) // After we write data on peripheral, we disconnect it. self.centralManager?.cancelPeripheralConnection(peripheral) // We stop scanning. self.centralManager?.stopScan() } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { print(&quot;\ndidDiscoverCharacteristicsFor&quot;) if let characteristic: CBCharacteristic = service.characteristics?.filter({ $0.uuid == self.characteristicCBUUID }).first { print(&quot;Matching characteristic&quot;) // To listen and read dynamic values self.discoveredPeripheral?.setNotifyValue(true, for: characteristic) // To read static values // self.discoveredPeripheral?.readValue(for: characteristic) } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { print(&quot;\ndidUpdateValueFor&quot;) // We read if let value: Data = characteristic.value { do { let receivedData: [String: String] = try PropertyListSerialization.propertyList(from: value, options: [], format: nil) as! [String: String] print(&quot;Value read is: \(receivedData)&quot;) self.blueEar?.didReceiveData() } catch let error { print(error) } } // We write do { print(&quot;\nWriting on peripheral.&quot;) let dict: [String: String] = [&quot;Yo&quot;: &quot;Lo&quot;] let data: Data = try PropertyListSerialization.data(fromPropertyList: dict, format: .binary, options: 0) self.discoveredPeripheral?.writeValue(data, for: characteristic, type: .withResponse) self.blueEar?.didSendData() } catch let error { print(error) } } func peripheralDidUpdateRSSI(_ peripheral: CBPeripheral, error: Error?) { print(&quot;\nperipheralDidUpdateRSSI&quot;) print(self.discoveredPeripheral?.rssi ?? &quot;&quot;) } func peripheralDidUpdateName(_ peripheral: CBPeripheral) { print(&quot;\nperipheralDidUpdateName&quot;) } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) { print(&quot;\ndidWriteValueFor&quot;) } func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { print(&quot;\ndidModifyServices&quot;) } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) { print(&quot;\ndidUpdateValueFor&quot;) } func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) { print(&quot;\ndidDiscoverIncludedServicesFor&quot;) } func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) { print(&quot;\ndidDiscoverDescriptorsFor&quot;) } func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { print(&quot;\ndidUpdateNotificationStateFor&quot;) } } ViewController import Foundation import Cocoa class ViewController: NSViewController { // MARK: - IBOutlet @IBOutlet weak var label: NSTextField! @IBOutlet weak var button: NSButton! // MARK: - Properties var manager: BluetoothManager? // MARK: - Lifecyle @IBAction func discover(_ sender: Any) { self.manager = BluetoothManager(delegate: self) self.manager?.scan() } } // MARK: - BlueEar extension ViewController: BlueEar { func didStartConfiguration() { self.label.stringValue = &quot;Start configuration 🎛&quot; } func didStartScanningPeripherals() { self.label.stringValue = &quot;Start scanning peripherals 👀&quot; } func didConnectPeripheral(name: String?) { self.label.stringValue = &quot;Did connect to: \(name ?? &quot;&quot;) 🤜🏽🤛🏽&quot; } func didDisconnectPeripheral(name: String?) { self.label.stringValue = &quot;Did disconnect: \(name ?? &quot;&quot;) 🤜🏽🤚🏽&quot; } func didSendData() { self.label.stringValue = &quot;Did send data ⬆️&quot; } func didReceiveData() { self.label.stringValue = &quot;Did received data ⬇️&quot; } func didFailConnection() { self.label.stringValue = &quot;Connection failed 🤷🏽‍♂️&quot; } } View Notas: No nosso exemplo, a Central vai começar a escanear por periféricos quando clicarmor num botão chamado Tap. Você só pode fazer alguma coisa com a central quando a função centralManagerDidUpdateState(: CBCentralManager) for chamada e o estado do periférico estiver .poweredOn. Note que o CBPeripheralDelegate é diferente do CBPeripheralManagerDelegate usado no periférico. Ambos são relacionados ao periférico, porém o CBPeripheralDelegate permite que a central escute eventos sobre o periférico. Ao optar por ler resultados dinâmicos, a central se inscreve em características do periférico, assim sendo alertada por meio de notificações se o periférico alterar seu valor no qual ela esteja inscrita. Quando a central descobre um periférico, devemos manter uma referência para ele, ou seja, devemos retê-lo fazendo com que uma variável dentro do nosso código o receba. Os dados são trasmitidos em formato de Data, então você deve transformar o que quer transmitir neste tipo de dados para poder ser recebido corretamente no outro lado. Resultado Na imagem, temos o respectivo: Log do periférico, iOS, macOS, Log da central. Referências CoreBlueetooth Agradecimentos Um agradecimento pra galera do Slack iOS Devs BR pela oportunidade. Um abraço, e até próxima. Leo</summary></entry><entry><title type="html">Integração Contínua com Travis-CI</title><link href="http://equinocios.com/ios/2017/03/26/integracao-continua-com-travis-ci/" rel="alternate" type="text/html" title="Integração Contínua com Travis-CI" /><published>2017-03-26T12:00:00+00:00</published><updated>2017-03-26T12:00:00+00:00</updated><id>http://equinocios.com/ios/2017/03/26/integracao-continua-com-travis-ci</id><content type="html" xml:base="http://equinocios.com/ios/2017/03/26/integracao-continua-com-travis-ci/">&lt;h1 id=&quot;integração-contínua-com-travisci&quot;&gt;Integração Contínua com Travis CI&lt;/h1&gt;
&lt;p&gt;Integração Contínua é, em outras palavras, a prática que busca manter o ambiente de desenvolvimento em pleno funcionamento após iterações feitas pelos devs do projeto. Para que isso ocorra, é necessário que a cada alteração no repositório, alguns itens do projeto sejam verificados, como a geração da &lt;em&gt;build&lt;/em&gt; e execução de testes, por exemplo.&lt;/p&gt;

&lt;p&gt;Você pode ler um pouco mais sobre o assunto &lt;a href=&quot;https://martinfowler.com/articles/continuousIntegration.html&quot;&gt;aqui (conteúdo em inglês)&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;travis-ci&quot;&gt;Travis CI&lt;/h1&gt;

&lt;p&gt;O Travis CI é um serviço dedicado exclusivamente à integração contínua. Ele opera integrado ao GitHub, assim, algumas tarefas são simplificadas, como a automação da obtenção do &lt;em&gt;source&lt;/em&gt; do projeto. Devido à integração, é necessário que seu projeto esteja hospedado no GitHub.&lt;/p&gt;

&lt;p&gt;O uso do Travis para projetos &lt;em&gt;open source&lt;/em&gt; é gratuito 🎉 (isso sem dúvida ajudou a popularizá-lo). Para utilizá-lo em projetos privados você terá que desembolsar alguns dólares, o valor mensal* vai de $69 no plano &lt;em&gt;Bootstrap&lt;/em&gt; até $489 💸 na opção &lt;em&gt;Premium&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Para começar a utilizar basta acessar &lt;a href=&quot;https://travis-ci.org&quot;&gt;travis-ci.org&lt;/a&gt; para projetos &lt;em&gt;open source&lt;/em&gt; ou &lt;a href=&quot;https://travis-ci.com&quot;&gt;travis-ci.com&lt;/a&gt; para projetos privados. O processo de &lt;em&gt;sign-up&lt;/em&gt; é bastante simples.&lt;/p&gt;

&lt;p&gt;* Informações de março, 2017&lt;/p&gt;

&lt;h1 id=&quot;benefícios&quot;&gt;Benefícios&lt;/h1&gt;

&lt;p&gt;Entre os benefícios do uso do Travis (ou qualquer outra solução de integração contínua) destaco a velocidade em que os problemas corriqueiros são encontrados, afinal, quanto mais rápido descobrirmos alguma adversidade, menor a chance de uma dor de cabeça das grandes. &lt;/p&gt;

&lt;p&gt;Outro ponto interessante é a integração realizada pelo Travis com o GitHub, onde a cada &lt;em&gt;commit&lt;/em&gt; ou &lt;em&gt;pull request&lt;/em&gt;, o Travis executa seu &lt;em&gt;job&lt;/em&gt; e marca visualmente se o ambiente foi comprometido ou não. Além também da geração dos tradicionais &lt;em&gt;badges&lt;/em&gt; informando o &lt;em&gt;status&lt;/em&gt; do projeto.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/serralvo/commits-travis.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Marcação visual do status da build&lt;/em&gt;&lt;/p&gt;

&lt;h1 id=&quot;hora-doshow&quot;&gt;Hora do Show&lt;/h1&gt;

&lt;p&gt;Para exemplificar o funcionamento do Travis criei um projeto para iOS em Swift 3. Nele, adicionei uma dependência que servirá para demonstrar como obter as bibliotecas ou frameworks do projeto.&lt;/p&gt;

&lt;p&gt;Esse projeto gerou três ítens para explorarmos: &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Será necessário gerenciar as dependências do projeto —  sim, é isso que você está pensando: CocoaPods.&lt;/li&gt;
  &lt;li&gt;Execução da &lt;em&gt;build&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Por fim, notificaremos o time sobre o &lt;em&gt;status&lt;/em&gt; do projeto.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;arquivotravisyml&quot;&gt;Arquivo .travis.yml&lt;/h1&gt;

&lt;p&gt;Para que essas tarefas listadas acima funcionem, nós precisaremos criar um arquivo que fornecerá instruções para o Travis. Aí é que entra o &lt;code class=&quot;highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Antes de começarmos a escrever o arquivo de configuração, precisamos entender como funciona o ciclo de vida do processo de &lt;em&gt;build&lt;/em&gt; do Travis:&lt;/p&gt;

&lt;p&gt;O Travis divide a execução do &lt;em&gt;job&lt;/em&gt; em duas etapas, a primeira delas é responsável pela atualização das dependências, seja do projeto, ou do ambiente. A segunda etapa é voltada para a execução da &lt;em&gt;build&lt;/em&gt; e outras tarefas relacionadas, como &lt;em&gt;tests&lt;/em&gt;, &lt;em&gt;reports&lt;/em&gt; e &lt;em&gt;deploy&lt;/em&gt;. Nessas etapas podemos detectar eventos do ciclo de vida e incluir ações de acordo com a necessidade do projeto.&lt;/p&gt;

&lt;p&gt;Para começarmos, o primeiro passo é realizar o cadastro no Travis. Para repositórios públicos ou privados, o funcionamento será o mesmo.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/serralvo/travis-ci-org.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;O próximo passo é “ativar” o Travis para o repositório desejado. Feito isso, no próximo &lt;em&gt;commit&lt;/em&gt; ou &lt;em&gt;pull request&lt;/em&gt;, o &lt;em&gt;job&lt;/em&gt; será executado.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/serralvo/start-travis.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Após o cadastro chegou a hora de criar o arquivo &lt;em&gt;.travis.yml&lt;/em&gt; na raiz do repositório. Feito isso, vamos incluir duas linhas: A primeira é usada para definir a linguagem do projeto (que é um valor obrigatório). No caso adicionaremos &lt;code class=&quot;highlighter-rouge&quot;&gt;objective-c&lt;/code&gt;. A segunda representa a imagem que será usada para fazer a build do projeto, no caso, adicionaremos &lt;code class=&quot;highlighter-rouge&quot;&gt;xcode8.1&lt;/code&gt;. Veja abaixo:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;language: objective-c
osx_image: xcode8.1
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Agora você pode estar assim: 🤔&lt;/p&gt;

&lt;p&gt;Ué, &lt;code class=&quot;highlighter-rouge&quot;&gt;objective-c&lt;/code&gt;?! Mas o projeto não está escrito em Swift? Sim, isso mesmo, até o momento o Travis utiliza o valor &lt;code class=&quot;highlighter-rouge&quot;&gt;objective-c&lt;/code&gt; para Swift e também para Objective-C.&lt;/p&gt;

&lt;h2 id=&quot;baixando-as-dependências&quot;&gt;Baixando as dependências&lt;/h2&gt;

&lt;p&gt;Se você já usou CocoaPods ao menos uma vez, sabe que basta executar &lt;code class=&quot;highlighter-rouge&quot;&gt;pod install&lt;/code&gt; para obter as dependências do projeto. No ambiente do Travis isso é um pouco diferente: se o &lt;code class=&quot;highlighter-rouge&quot;&gt;Podfile&lt;/code&gt; estiver na raiz do projeto, o Travis fará o &lt;em&gt;fetch&lt;/em&gt; automaticamente, caso contrário, basta indicar no &lt;code class=&quot;highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt; qual o local de tal arquivo:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;podfile: path/to/Podfile
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Se o seu projeto usa outro gerenciador de dependências, é possível fazer &lt;em&gt;override&lt;/em&gt; da etapa de &lt;code class=&quot;highlighter-rouge&quot;&gt;install&lt;/code&gt; para realizar a instalação de acordo com sua necessidade:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;install: sh dependencies.sh
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;build-e-sucesso&quot;&gt;Build e Sucesso&lt;/h2&gt;

&lt;p&gt;Após obter as dependências do projeto, basta apenas configurar alguns parâmetros para a execução da &lt;em&gt;build&lt;/em&gt;. Esses parâmetros envolvem alguns ítens necessários para continuar o processo. São eles:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Path&lt;/em&gt; do &lt;code class=&quot;highlighter-rouge&quot;&gt;xcworkspace&lt;/code&gt; ou &lt;code class=&quot;highlighter-rouge&quot;&gt;xcproject&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Algum &lt;em&gt;scheme&lt;/em&gt; com a opção &lt;em&gt;shared&lt;/em&gt; ativada (&lt;a href=&quot;http://help.apple.com/xcode/mac/8.0/#/dev5426ddfcf&quot;&gt;saiba mais aqui&lt;/a&gt;).&lt;/li&gt;
  &lt;li&gt;SDK que será usado (no caso estamos usando &lt;code class=&quot;highlighter-rouge&quot;&gt;iphonesimulator&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Conhecendo tais parâmetros é hora de realizar a &lt;em&gt;build&lt;/em&gt; do projeto, para isso, vamos adicionar na etapa &lt;code class=&quot;highlighter-rouge&quot;&gt;script&lt;/code&gt; a chamada do &lt;code class=&quot;highlighter-rouge&quot;&gt;xcodebuild&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;script:
  - xcodebuild -workspace DemoTravisCI.xcworkspace -scheme 'DemoTravisCI' -sdk iphonesimulator build
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Sendo assim, no momento o arquivo &lt;code class=&quot;highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt; possui o seguinte conteúdo:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;language: objective-c
osx_image: xcode8.1

script:
  - xcodebuild -workspace DemoTravisCI.xcworkspace  -scheme DemoTravisCI -sdk iphonesimulator build
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;notificações&quot;&gt;Notificações&lt;/h2&gt;

&lt;p&gt;Para detectar possíveis problemas com o projeto, é interessante compartilhar o status da &lt;em&gt;build&lt;/em&gt; com o time a cada iteração. O Travis provê diversas opções para notificações, começando pelo envio de e-mails e abrindo um leque de possibilidades graças às integrações. No nosso caso, vamos ser avisados via Slack 📢.&lt;/p&gt;

&lt;p&gt;Para isso, o primeiro passo é adicionar uma &lt;a href=&quot;https://my.slack.com/services/new/travis&quot;&gt;nova integração ao Slack&lt;/a&gt;. Após selecionar o time e as demais opções, na própria página do Slack você encontrará o conteúdo que deve ser adicionado ao seu arquivo de configuração.&lt;/p&gt;

&lt;p&gt;Concluído tal passo, vamos incluir a chave &lt;code class=&quot;highlighter-rouge&quot;&gt;notifications&lt;/code&gt; no arquivo &lt;code class=&quot;highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;notifications:
  slack: yourteam:G1P621hDDwEH3pXeCcJpck8i
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Importante: Caso seu projeto seja aberto, é recomendado criptografar a chave. Esse é um processo bastante simples e você pode saber mais &lt;a href=&quot;https://docs.travis-ci.com/user/encryption-keys/&quot;&gt;aqui&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;considerações-finais&quot;&gt;Considerações Finais&lt;/h1&gt;

&lt;p&gt;Ferramentas de integração contínua são realidade no mercado e fazem parte da rotina de qualquer grande projeto de software. Algumas demandam maior esforço para que sejam configuradas (principalmente ferramentas &lt;em&gt;self-hosted&lt;/em&gt;), outras não, como é o caso do Travis, onde basta um arquivo de marcação para que a mágica aconteça.&lt;/p&gt;

&lt;p&gt;Se você se interessou pelo assunto e deseja implantar tal processo em seus projetos, e por alguma limitação não irá conseguir utilizar o Travis, saiba que existem diversas opções, como Jenkins, Xcode Server, CircleCI, entre outras.&lt;/p&gt;

&lt;p&gt;Para finalizar, Integração Contínua é um dos pilares do desenvolvimento ágil, e podemos considerar que também é um passo para a Entrega Contínua, mas isso é assunto para outro artigo 🙃.&lt;/p&gt;

&lt;p&gt;Um obrigado especial ao &lt;a href=&quot;https://github.com/rogerluan&quot;&gt;Roger Oba&lt;/a&gt; e também ao &lt;a href=&quot;https://github.com/ciceroduarte&quot;&gt;Cícero Duarte&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;referencias&quot;&gt;Referencias:&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://unsplash.com/photos/zlABb6Gke24&quot;&gt;Imagem da Capa - Relax by Clem Onojeghuo&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://docs.travis-ci.com/user/getting-started/&quot;&gt;Getting started&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://docs.travis-ci.com/user/languages/objective-c/&quot;&gt;Building an Objective-C Project&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://docs.travis-ci.com/user/notifications/&quot;&gt;Notifications&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Fabricio Serralvo</name></author><category term="ios" /><summary type="html">Integração Contínua com Travis CI Integração Contínua é, em outras palavras, a prática que busca manter o ambiente de desenvolvimento em pleno funcionamento após iterações feitas pelos devs do projeto. Para que isso ocorra, é necessário que a cada alteração no repositório, alguns itens do projeto sejam verificados, como a geração da build e execução de testes, por exemplo.</summary></entry><entry><title type="html">Gerenciando subscriptions com In-App Purchases</title><link href="http://equinocios.com/subscription/2017/03/25/Gerenciando-subscriptions-com-In-App-Purchases/" rel="alternate" type="text/html" title="Gerenciando subscriptions com In-App Purchases" /><published>2017-03-25T09:00:00+00:00</published><updated>2017-03-25T09:00:00+00:00</updated><id>http://equinocios.com/subscription/2017/03/25/Gerenciando-subscriptions-com-In-App-Purchases</id><content type="html" xml:base="http://equinocios.com/subscription/2017/03/25/Gerenciando-subscriptions-com-In-App-Purchases/">&lt;blockquote&gt;
  &lt;p&gt;Renan Protector (&lt;a href=&quot;https://twitter.com/reprotector&quot; target=&quot;_blank&quot;&gt;@reprotector&lt;/a&gt;) é desenvolvedor iOS desde 2009. Atualmente Indie Dev, é Co-Founder do (&lt;a href=&quot;https://getblogo.com&quot; target=&quot;_blank&quot;&gt;Blogo&lt;/a&gt;) e do (&lt;a href=&quot;https://spacecoworking.com&quot; target=&quot;_blank&quot;&gt;Space Coworking&lt;/a&gt;).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Em Junho de 2016 a Apple modificou sua política de subscriptions na App Store, permitindo que várias categorias de aplicativos possam utilizar esse modelo de negócios. A assinatura funciona como um In-App Purchase e toda a parte de pagamento é feito pela própria App Store. O foco desse artigo está na gestão das assinaturas, por isso não falaremos como implementar IAP (In-App Purchase) dentro do seu aplicativo. &lt;a href=&quot;https://developer.apple.com/in-app-purchase/&quot; target=&quot;_blank&quot;&gt;Clique Aqui&lt;/a&gt; para saber mais sobre IAP.&lt;/p&gt;

&lt;p&gt;Iremos falar sobre duas possibilidades: &lt;strong&gt;Assinatura apenas no app&lt;/strong&gt; e &lt;strong&gt;Assinatura em vários ambientes&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;apenas-em-1-app&quot;&gt;Apenas em 1 App&lt;/h2&gt;
&lt;p&gt;Quando a assinatura é apenas para um único app iOS, não é preciso fazer muita coisa. O próprio app deve gerenciar a assinatura do usuário. Após completar a compra do IAP, o método &lt;code class=&quot;highlighter-rouge&quot;&gt;- (void)completeTransaction:(SKPaymentTransaction *)transaction&lt;/code&gt; será chamado e a partir daí as funcionalidades já podem ser liberadas para o usuário.&lt;/p&gt;

&lt;p&gt;Para verificar se o usuário é assinante e se a assinatura está em dia, basta verificar o receipt&lt;a href=&quot;#what_is_receipt&quot;&gt;*&lt;/a&gt; do aplicativo. Recomendo a utilização do &lt;a href=&quot;https://github.com/rmaddy/VerifyStoreReceiptiOS&quot; target=&quot;_blank&quot;&gt;VerifyStoreReceiptiOS&lt;/a&gt;, pois facilita muito a leitura dos campos do receipt dentro do aplicativo.&lt;/p&gt;

&lt;p&gt;Para saber como validar um receipt, veja o item: &lt;a href=&quot;#validate_receipt&quot;&gt;O que verificar nesse receipt?&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;múltiplos-apps-e-web&quot;&gt;Múltiplos apps e Web&lt;/h2&gt;

&lt;p&gt;Quando a assinatura vai ser usada em vários ambientes, é necessário que você sincronize os dados da App Store. Você precisará de um serviço web para gerenciar as assinaturas e validá-las. Isso significa que seu aplicativo precisará de login para identificar seus usuários e suas respectivas assinaturas.&lt;/p&gt;

&lt;h3 id=&quot;chega-de-papo-como-faço-isso-no-meu-app&quot;&gt;Chega de papo, como faço isso no meu app?&lt;/h3&gt;

&lt;p&gt;Ao finalizar a compra do IAP, o seguinte método será chamado: &lt;code class=&quot;highlighter-rouge&quot;&gt;- (void)completeTransaction:(SKPaymentTransaction *)transaction&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Nesse momento, o receipt do seu app já estará atualizado com os dados de compra do IAP e você deverá enviá-lo para sua API. Sua API deve validar os dados junto à App Store para se certificar que o receipt é verdadeiro e original. Para saber mais sobre a validação do receipt na App Store, &lt;a href=&quot;https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html#//apple_ref/doc/uid/TP40010573-CH104-SW1&quot; target=&quot;_blank&quot;&gt;clique aqui.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Em Ruby, a validação pode ser feito com o código abaixo, não esqueça de adicionar seu Token no request:&lt;/p&gt;

&lt;div class=&quot;language-ruby highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;	&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;validate_receipt_remote&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;receipt_base64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  
	  &lt;span class=&quot;n&quot;&gt;receipt_base64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gsub!&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;' '&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;'+'&lt;/span&gt;
	  &lt;span class=&quot;n&quot;&gt;params_json&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;{ &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;receipt-data&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;receipt_base64&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;password&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\”&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;SEU TOKEN AQUI&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\”&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;}”
	  uri = URI(&quot;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;ss&quot;&gt;:/&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;buy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;itunes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;apple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;com&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;) # Use &quot;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;ss&quot;&gt;:/&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;buy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;itunes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;apple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;com&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot; for production
	  Net::HTTP.start(uri.host, uri.port, :use_ssl =&amp;gt; uri.scheme == 'https') do |http|
	    response = http.post('/verifyReceipt', params_json)	    
	    return JSON.parse(response.body)
	  end
	end
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Um exemplo de resposta dessa requisição (mantive apenas os campos que considero importante):&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;status&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   =&amp;gt;0,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;environment&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;Production&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;receipt&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   =&amp;gt;   {&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;receipt_type&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;Production&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;app_item_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;977160124,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;bundle_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;com.Blogo.ios&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;application_version&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;251&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;receipt_creation_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2017-03-12 11:22:41      Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;request_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2017-03-24 17:22:53      Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;original_purchase_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-10-16 03:54:25      Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;original_application_version&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;215&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;in_app&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      =&amp;gt;      [&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         {&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;product_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;com.blogo.pro.ios.month&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;transaction_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;120000262038036&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;original_transaction_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;120000262038036&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;purchase_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-10-16 05:45:23            Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;original_purchase_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-10-16 05:45:24            Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;expires_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-11-16 06:45:23            Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;is_trial_period&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;            =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;true&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         }&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      ]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   },&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;latest_receipt_info&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   =&amp;gt;   &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;product_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;com.blogo.pro.ios.month&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;transaction_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;120000262038036&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;original_transaction_id&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;120000262038036&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;purchase_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-10-16 05:45:23         Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;original_purchase_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-10-16 05:45:24         Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;expires_date&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;2016-11-16 06:45:23         Etc/GMT&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;is_trial_period&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;         =&amp;gt;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;true&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;      }&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   &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;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;latest_receipt&quot;&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;   =&amp;gt;&quot;MIIXOwYJKoZIhvcNAQc….”&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h3 id=&quot;o-que-verificar-nesse-receipt&quot;&gt;&lt;a name=&quot;validate_receipt&quot;&gt;&lt;/a&gt;O que verificar nesse receipt?&lt;/h3&gt;

&lt;p&gt;A primeira coisa que deve ser verificada é se os campos &lt;code class=&quot;highlighter-rouge&quot;&gt;bundle_id&lt;/code&gt; e &lt;code class=&quot;highlighter-rouge&quot;&gt;app_item_id&lt;/code&gt; conferem com o do seu aplicativo.&lt;/p&gt;

&lt;p&gt;Nos dados do IAP, você deve validar a data de expiração e deve atrelar o &lt;code class=&quot;highlighter-rouge&quot;&gt;transaction_id&lt;/code&gt; da assinatura com o usuário. O &lt;code class=&quot;highlighter-rouge&quot;&gt;transaction_id&lt;/code&gt; deve ser um dado único por assinatura, por usuário. Por que isso? Se não for salvo dessa forma, o usuário pode dar logout no aplicativo, logar com outro usuário e assinar o IAP novamente. Como já está pago na App Store, a Apple vai retornar para o método &lt;code class=&quot;highlighter-rouge&quot;&gt;completeTransaction&lt;/code&gt; como se a transação tivesse sido bem sucedida. Isso é &lt;strong&gt;MUITO IMPORTANTE&lt;/strong&gt; para evitar fraudes no seu app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Importante!&lt;/strong&gt; Sempre use os dados do &lt;code class=&quot;highlighter-rouge&quot;&gt;latest_receipt_info&lt;/code&gt;. O receipt é um arquivo local e os dados do &lt;code class=&quot;highlighter-rouge&quot;&gt;latest_receipt_info&lt;/code&gt; são os últimos dados encontrados no serviço da Apple.&lt;/p&gt;

&lt;p&gt;Depois de validado, você deve guardar o arquivo de receipt na sua nuvem. Ele será usado para verificar se o usuário renovou a assinatura.&lt;/p&gt;

&lt;h3 id=&quot;como-sei-se-o-usuário-é-um-assinante&quot;&gt;Como sei se o usuário é um assinante?&lt;/h3&gt;

&lt;p&gt;Seu app deve se comunicar com sua base de dados online, perguntando se ele é um assinante ou não. Lembre-se que o usuário pode ter assinado em outro dispositivo, veja qual é o momento ideal para perguntar pro seu servidor se ele está ativo ou não. Em meus apps iOS, costumo verificar logo na abertura do app ou logo que o dispositivo tenha acesso a internet, caso estivesse sem interent no momento da abertura. Também costumo verificar novamente antes de entrar no processo de assinatura.&lt;/p&gt;

&lt;h3 id=&quot;ótimo-já-sei-que-o-usuário-assinou-meu-iap-e-quando-acabar-o-período-como-sei-que-ele-renovou&quot;&gt;Ótimo, já sei que o usuário assinou meu IAP. E quando acabar o período, como sei que ele renovou?&lt;/h3&gt;

&lt;p&gt;As assinaturas são renovadas 1 dia antes delas expirarem, mas pode ocorrer problemas no pagamento e o processo de renovação pode levar mais tempo. Minha experiência mostra que assinaturas podem ser renovadas automaticamente até 1 dia depois dela expirar. Portanto, não bloqueie as funcionalidades da assinatura assim que ela expirar. Espere pelo menos 1 dia pra ter certeza que ela não foi renovada.&lt;/p&gt;

&lt;p&gt;Para verificar se a assinatura foi renovada ou não, devemos pegar o receipt que foi salvo no momento da assinatura e fazer o mesmo processo de validação. Faça a validação do receipt pelo link da Apple e verifique o &lt;code class=&quot;highlighter-rouge&quot;&gt;latest_receipt_info&lt;/code&gt;.  Caso a assinatura tenha sido renovada, um novo item de IAP terá sido criado. Basta, então, adicionar o novo transaction_id no seu banco de dados e liberar o uso das funcionalidades no seu aplicativo.&lt;/p&gt;

&lt;p&gt;Abaixo um exemplo de um receipt com assinaturas renovadas. Repare que o usuário entrou em trial no dia 16/10/16, renovou automaticamente a assinatura em 16/11/16 e não renovou no período de Janeiro a Março. Em 12/03/17 o usuário se inscreveu novamente em uma assinatura.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&quot;latest_receipt_info&quot;   =&amp;gt;   [ 
      { 
         &quot;product_id&quot;         =&amp;gt;&quot;com.blogo.pro.ios.month&quot;,
         &quot;transaction_id&quot;         =&amp;gt;&quot;120000262038036&quot;,
         &quot;original_transaction_id&quot;         =&amp;gt;&quot;120000262038036&quot;,
         &quot;purchase_date&quot;         =&amp;gt;&quot;2016-10-16 05:45:23         Etc/GMT&quot;,
         &quot;original_purchase_date&quot;         =&amp;gt;&quot;2016-10-16 05:45:24         Etc/GMT&quot;,
         &quot;expires_date&quot;         =&amp;gt;&quot;2016-11-16 06:45:23         Etc/GMT&quot;,
         &quot;is_trial_period&quot;         =&amp;gt;&quot;true&quot;
      },
      { 
         &quot;product_id&quot;         =&amp;gt;&quot;com.blogo.pro.ios.month&quot;,
         &quot;transaction_id&quot;         =&amp;gt;&quot;120000269815092&quot;,
         &quot;original_transaction_id&quot;         =&amp;gt;&quot;120000262038036&quot;,
         &quot;purchase_date&quot;         =&amp;gt;&quot;2016-11-16 06:45:23         Etc/GMT&quot;,
         &quot;original_purchase_date&quot;         =&amp;gt;&quot;2016-10-16 05:45:24         Etc/GMT&quot;,
         &quot;expires_date&quot;         =&amp;gt;&quot;2016-12-16 06:45:23         Etc/GMT&quot;,
         &quot;is_trial_period&quot;         =&amp;gt;&quot;false&quot;
      },
      { 
         &quot;product_id&quot;         =&amp;gt;&quot;com.blogo.pro.ios.month&quot;,
         &quot;transaction_id&quot;         =&amp;gt;&quot;120000303300763&quot;,
         &quot;original_transaction_id&quot;         =&amp;gt;&quot;120000262038036&quot;,
         &quot;purchase_date&quot;         =&amp;gt;&quot;2017-03-12 11:22:40         Etc/GMT&quot;,
         &quot;original_purchase_date&quot;         =&amp;gt;&quot;2016-10-16 05:45:24         Etc/GMT&quot;,
         &quot;expires_date&quot;         =&amp;gt;&quot;2017-04-12 11:22:40         Etc/GMT&quot;,
         &quot;is_trial_period&quot;         =&amp;gt;&quot;false&quot;
      }
   ]
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;conclusão&quot;&gt;Conclusão&lt;/h2&gt;

&lt;p&gt;A gestão de subscriptions com a App Store não é tão complicada quanto parece ser. Quando a assinatura é pra apenas um app, não é preciso fazer muitas coisa e o processo de validação é bem simples. Já para múltiplos ambientes, a documentação da Apple não é muito clara sobre como verificar se um usuário renovou a assinatura ou não. Esse artigo tenta ajudar a desvendar o mistério do &lt;code class=&quot;highlighter-rouge&quot;&gt;latest_receipt_info&lt;/code&gt; que não é muito claro na documentação da Apple. Dúvidas e sugestões podem ser colocadas no Slack iOSDevBr, não deixe de entrar lá!&lt;/p&gt;

&lt;h4 id=&quot;notas-de-rodapé&quot;&gt;Notas de Rodapé:&lt;/h4&gt;

&lt;p&gt;&lt;a name=&quot;what_is_receipt&quot;&gt;&lt;/a&gt;
&lt;strong&gt;Receipt&lt;/strong&gt;: Todo aplicativo, seja ele pago ou gratuito, possui um “recibo de compra” embutido. Esse arquivo contém dados importantes que devem ser usados para evitar fraudes. &lt;a href=&quot;https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1&quot; target=&quot;_blank&quot;&gt;Clique aqui&lt;/a&gt; para saber mais sobre os campos de um receipt.&lt;/p&gt;</content><author><name>Renan Protector</name></author><category term="subscription" /><summary type="html">Renan Protector (@reprotector) é desenvolvedor iOS desde 2009. Atualmente Indie Dev, é Co-Founder do (Blogo) e do (Space Coworking).</summary></entry><entry><title type="html">Sincronização de dados com CloudKit</title><link href="http://equinocios.com/cloudkit/2017/03/24/Sincronizacao-de-dados-com-CloudKit/" rel="alternate" type="text/html" title="Sincronização de dados com CloudKit" /><published>2017-03-24T12:00:00+00:00</published><updated>2017-03-24T12:00:00+00:00</updated><id>http://equinocios.com/cloudkit/2017/03/24/Sincronizacao-de-dados-com-CloudKit</id><content type="html" xml:base="http://equinocios.com/cloudkit/2017/03/24/Sincronizacao-de-dados-com-CloudKit/">&lt;blockquote&gt;
  &lt;p&gt;Guilherme Rambo (&lt;a href=&quot;https://twitter.com/_inside&quot; target=&quot;_blank&quot;&gt;@_inside&lt;/a&gt;) é desenvolvedor iOS na &lt;a href=&quot;https://peixeurbano.com&quot; target=&quot;_blank&quot;&gt;Peixe Urbano&lt;/a&gt;, criador do &lt;a href=&quot;https://getbrowserfreedom.com&quot;&gt;BrowserFreedom&lt;/a&gt;, &lt;a href=&quot;https://itunes.apple.com/app/chibistudio/id1135307199&quot;&gt;ChibiStudio&lt;/a&gt; e criador de diversos projetos open-source, incluindo o &lt;a href=&quot;https://github.com/insidegui/WWDC&quot;&gt;app da WWDC para macOS&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;O CloudKit foi lançado pela Apple em 2014 e desde então recebeu diversas melhorias, como a possibilidade de utilizá-lo fora das plataformas da Apple, a liberação do seu uso em apps fora da App Store no macOS e a disponibilidade do framework no watchOS, completando o círculo de plataformas da Apple suportadas.&lt;/p&gt;

&lt;p&gt;Acredito que a tecnologia ainda não esteja sendo explorada em todo o seu potencial pelos desenvolvedores nas plataformas da Apple, seja por medo ou desconhecimento. Pretendo ajudar a mudar isso com este artigo.&lt;/p&gt;

&lt;h1 id=&quot;posso-usar-cloudkit&quot;&gt;Posso usar CloudKit?&lt;/h1&gt;

&lt;p&gt;Infelizmente, a primeira pergunta que todos se fazem quando juntamos as palavras “Apple” e “nuvem” na mesma frase é: “dá pra usar sem medo?”. De fato, a Apple não tem um histórico muito bom quando o assunto é serviços na nuvem, desde &lt;a href=&quot;http://gizmodo.com/5033442/steve-jobss-entire-mobileme-is-fail-email&quot;&gt;o fiasco do Mobile.me&lt;/a&gt; até &lt;a href=&quot;http://www.imore.com/debug-12-icloud-core-data-sync&quot;&gt;o problema do iCloud Core Data&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A boa notícia é que em se tratando de CloudKit, a coisa é bem diferente. Eu arrisco afirmar que talvez seja a tecnologia da Apple na nuvem mais confiável de todas. Mas como eu sei que apenas minhas palavras não serão o suficiente para convencê-lo de que uma tecnologia da Apple na nuvem é confiável, vou deixar que você mesmo decida. Se você usa o aplicativo Notas da Apple, saiba que ele usa CloudKit. Outros exemplos de uso do CloudKit pela própria Apple são o compartilhamento de atividades no Apple Watch, o app Fotos e o iCloud Drive.&lt;/p&gt;

&lt;p&gt;Se os apps citados acima funcionam bem pra você, então pode ficar tranquilo e usar o CloudKit sem medo. Se eles não funcionam bem pra você, eu não vou conseguir convencê-lo de que a tecnologia é confiável 😅&lt;/p&gt;

&lt;p&gt;Um detalhe importante a ser colocado é que a confiabilidade do CloudKit também depende muito da implementação. Como a API não automatiza muita coisa, cabe a cada desenvolvedor usá-la da melhor maneira para criar uma experiência agradável e confiável ao usuário, o que nos leva ao próximo ponto:&lt;/p&gt;

&lt;h1 id=&quot;devo-usar-cloudkit&quot;&gt;Devo usar CloudKit?&lt;/h1&gt;

&lt;p&gt;Mesmo que você esteja convencido de que pode usar o CloudKit sem medo, isso não significa que você deva usá-lo, afinal existem aplicações para as quais ele é mais indicado e outras para as quais existem ferramentas melhores, não estamos falando aqui de uma bala de prata.&lt;/p&gt;

&lt;h2 id=&quot;onde-usar-cloudkit&quot;&gt;Onde usar CloudKit&lt;/h2&gt;

&lt;p&gt;Estas são as situações para as quais o CloudKit é altamente indicado:&lt;/p&gt;

&lt;h3 id=&quot;sincronizar-dados-privados-dos-usuários-entre-vários-dispositivos&quot;&gt;Sincronizar dados privados dos usuários entre vários dispositivos&lt;/h3&gt;

&lt;p&gt;Este talvez seja o uso mais óbvio, que é a sincronização dos dados privados de um usuário entre os vários dispositivos daquele usuário.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exemplo:&lt;/strong&gt; um aplicativo de notas ou todo list onde o usuário pode criar e ler notas em qualquer dispositivo que possua associado à sua conta do iCloud (Mac, iPhone, iPad, Apple Watch, etc) ou até mesmo numa interface web.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Alternativas: Realm Mobile Platform, Firebase, iCloud KVS ou iCloud Documents (dependendo do caso)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;armazenar-configurações-remotas-do-aplicativo&quot;&gt;Armazenar configurações remotas do aplicativo&lt;/h3&gt;

&lt;p&gt;Utilizando o banco de dados público do seu container é possível armazenar dados que são compartilhados por todas as instâncias do seu app, por todos os usuários, mesmo que não estejam autenticados com uma conta do iCloud.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exemplo:&lt;/strong&gt; um aplicativo que em épocas festivas (Carnaval, Natal, etc) muda as cores do seu tema poderia armazenar os códigos das cores no banco de dados público do CloudKit. Desta maneira, as cores poderiam ser alteradas remotamente sem a necessidade de um servidor próprio ou atualização do app.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Alternativas: Realm Mobile Platform, Firebase ou servidor próprio&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;sincronizar-dados-entre-vários-apps-do-mesmo-desenvolvedor&quot;&gt;Sincronizar dados entre vários apps do mesmo desenvolvedor&lt;/h3&gt;

&lt;p&gt;Se você tem uma família de apps e quer que os dados dos seus usuários sejam acessíveis em todos os seus apps, é possível utilizar um container compartilhado entre todos os apps desta família de modo que os usuários tenham acesso aos mesmos dados em todos os apps. Isto também se aplica a configurações (item acima), poderiam ser compartilhadas por todos os apps que utilizam o mesmo container.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Alternativas: servidor próprio (devem existir outros serviços que suportem isto, mas não tenho conhecimento para indicar algum)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;utilizar-a-conta-do-icloud-do-usuário-como-forma-de-autenticação&quot;&gt;Utilizar a conta do iCloud do usuário como forma de autenticação&lt;/h3&gt;

&lt;p&gt;Você pode utilizar a conta do iCloud do usuário apenas como meio de autenticação para algum outro app ou serviço&lt;/p&gt;

&lt;h3 id=&quot;enviar-notificações&quot;&gt;Enviar notificações&lt;/h3&gt;

&lt;p&gt;Sim, é possível enviar notificações usando o CloudKit, eliminando a necessidade de utilizar um serviço terceirizado ou um servidor próprio para este fim.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Alternativas: Firebase ou servidor próprio&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;onde-não-usar-cloudkit&quot;&gt;Onde NÃO usar CloudKit&lt;/h2&gt;

&lt;p&gt;Agora que já vimos alguns exemplos de onde o CloudKit é extremamente indicado, vamos a dois exemplos de onde ele é altamente contra-indicado:&lt;/p&gt;

&lt;h3 id=&quot;não-armazenamento-e-sincronização-de-documentos&quot;&gt;NÃO: Armazenamento e sincronização de documentos&lt;/h3&gt;

&lt;p&gt;Se o seu app trabalha primariamente com documentos, o CloudKit não é a ferramenta mais indicada para armazenamento e sincronização dos mesmos. Neste caso o ideal seria usar iCloud Drive, Dropbox ou outros serviços similares. É possível armazenar arquivos grandes como fotos e vídeos no CloudKit, mas ele pode não ser a melhor solução se a função principal do seu app é lidar com documentos.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exemplo:&lt;/strong&gt; editores de texto estilo Pages, editores de imagens estilo Pixelmator, Sketch, etc&lt;/p&gt;

&lt;h3 id=&quot;não-sincronização-de-preferências-do-usuário&quot;&gt;NÃO: Sincronização de preferências do usuário&lt;/h3&gt;

&lt;p&gt;Para armazenar simples preferências do usuário ou quantidades muito pequenas de informação, utilize &lt;a href=&quot;https://developer.apple.com/library/content/documentation/General/Conceptual/iCloudDesignGuide/Chapters/DesigningForKey-ValueDataIniCloud.html&quot;&gt;iCloud KVS&lt;/a&gt; (&lt;code class=&quot;highlighter-rouge&quot;&gt;NSUbiquitousKeyValueStore&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exemplo:&lt;/strong&gt; seu app tem uma opção para mostrar ou esconder uma barra de ferramentas e você quer que esta configuração seja propagada para todos os dispositivos do usuário&lt;/p&gt;

&lt;h2 id=&quot;por-que-não-usar-alguma-alternativa&quot;&gt;Por que não usar alguma alternativa?&lt;/h2&gt;

&lt;p&gt;O CloudKit é uma tecnologia da própria Apple que já vem instalada em todos os dispositivos, não requer uma autenticação além da conta do iCloud que os usuários já possuem, tem funcionalidades muito poderosas e tem uma grande chance de continuar existindo por um bom tempo. Estes são os principais motivos que me fazem preferir o CloudKit em vez de soluções de terceiros.&lt;/p&gt;

&lt;h1 id=&quot;quanto-custa&quot;&gt;Quanto custa?&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/free-with-limits.gif&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Esta é uma dúvida comum quando estamos falando de serviços de sincronização e com o CloudKit não é diferente. Esta questão do preço é comumente confundida pelos desenvolvedores, então vou explicar aqui da forma mais simples possível.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w87fOAG8fjk&amp;amp;t=1h36m36s&quot;&gt;Como disse Craig Federighi na introdução do CloudKit&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;O CloudKit é grátis… (cof cof) com limites (cof cof) 🙊&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Mas o que isso significa?&lt;/p&gt;

&lt;p&gt;Colocando de forma simples: &lt;strong&gt;O CLOUDKIT É GRÁTIS, PONTO&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;O que a Apple fez foi criar um sistema que previna abusos, dessa forma, se você fizer um uso ‘normal’ do serviço, ele será sempre grátis.&lt;/p&gt;

&lt;p&gt;Conforme foi dito na session 231 da WWDC de 2014 (tradução livre):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Nós não queremos previnir uso legítimo&lt;/p&gt;

  &lt;p&gt;Nós só queremos evitar que alguém abuse do CloudKit&lt;/p&gt;

  &lt;p&gt;Os números que nós informamos aqui aumentam com o número de usuários que você tem&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;E tem mais: se você utiliza apenas o &lt;strong&gt;banco de dados privado&lt;/strong&gt; do CloudKit (que é o uso mais comum), o uso dele conta para a cota do usuário, ou seja, quem paga é o usuário e não você.&lt;/p&gt;

&lt;p&gt;Os limites para uso do banco de dados público do CloudKit aumentam com o número de usuários do seu app, conforme pode ser visto na simulação abaixo que fiz no site da Apple:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/quota.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Lembrando que estes limites são para o banco de dados público, que é compartilhado por todos os usuários do seu app, o uso do banco de dados privado de cada usuário conta para a cota daquele usuário no iCloud, ou seja, jamais terá custo algum para você.&lt;/p&gt;

&lt;h1 id=&quot;mão-na-massa&quot;&gt;Mão na massa&lt;/h1&gt;

&lt;p&gt;Passada esta introdução, hora de colocarmos a mão na massa. Vou explicar vários conceitos sobre o CloudKit e ao mesmo tempo apresentar pequenos exemplos de como são usados na prática 😉&lt;/p&gt;

&lt;h2 style=&quot;color:#C86D6C&quot;&gt;Ativando o CloudKit no seu projeto&lt;/h2&gt;

&lt;p&gt;O primeiro passo para usarmos o CloudKit é habilitar ele no painel Capabilities do Xcode.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/cloudkit-enable.gif&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ao habilitarmos o CloudKit no projeto, o Xcode se comunica com os servidores da Apple para atualizar o nosso provisioning profile e também para criar o container padrão para o app.&lt;/p&gt;

&lt;p&gt;Perceba que ao ativar o CloudKit, o Xcode ativou automaticamente Push Notifications, porque as subscriptions do CloudKit utilizam push notifications (falarei mais sobre isso depois).&lt;/p&gt;

&lt;h2 id=&quot;container&quot;&gt;Container&lt;/h2&gt;

&lt;p&gt;Um container nada mais é do que uma caixinha onde você coloca os dados dos seus usuários. O container é o pai de todos os dados e geralmente será diferente para cada aplicativo seu, embora seja possível compartilhar um container entre vários apps. Por padrão, quando você habilita CloudKit no seu projeto, o Xcode cria um container com o bundle identifier do seu app. Outro detalhe a ser apontado é que um único app pode acessar vários containers.&lt;/p&gt;

&lt;p&gt;Containers são representados por objetos do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Acessando o container padrão&lt;/h3&gt;

&lt;p&gt;Acessar o container padrão do app é bem fácil: basta utilizar o método &lt;code class=&quot;highlighter-rouge&quot;&gt;default&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;container&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CKContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Criando e acessando um container personalizado&lt;/h3&gt;

&lt;p&gt;Se você pretende compartilhar dados no CloudKit com outros apps desenvolvidos por você ou por versões para diferentes plataformas do mesmo app (ex: entre macOS e iOS), você deve criar um container próprio para isso.&lt;/p&gt;

&lt;p&gt;O nome do container deve seguir o mesmo esquema dos bundle identifiers: DNS reverso. No meu caso, criei um container chamado &lt;code class=&quot;highlighter-rouge&quot;&gt;iCloud.br.com.guilhermerambo.KitchenContainer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/custom-container.gif&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Com o container criado, basta usar o inicializador de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt; que aceita um &lt;code class=&quot;highlighter-rouge&quot;&gt;identifier&lt;/code&gt; como parâmetro e passar o nome que demos ao nosso container.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;containerIdentifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;iCloud.br.com.guilhermerambo.KitchenContainer&quot;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;secondContainer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CKContainer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;identifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;containerIdentifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Se você for usar somente o container padrão do app, basta usar &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer.default()&lt;/code&gt;, nos demais exemplos deste artigo utilizarei o container default para que o código fique mais breve.&lt;/p&gt;

&lt;h2 id=&quot;database&quot;&gt;Database&lt;/h2&gt;

&lt;p&gt;Database é o banco de dados onde você irá armazenar os registros que seu app usa. Bancos de dados são representados  por objetos do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKDatabase&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Todo container do CloudKit contém três bancos de dados:&lt;/p&gt;

&lt;h3 id=&quot;private-database&quot;&gt;Private database&lt;/h3&gt;

&lt;p&gt;Este é o banco de dados privado, onde os dados privados dos seus usuários ficarão armazenados. Somente um dispositivo do usuário autenticado na conta do iCloud consegue ter acesso aos registros armazenados neste banco de dados.&lt;/p&gt;

&lt;p&gt;Sendo assim, você como desenvolvedor do app não consegue ver os dados dos seus usuários. O dashboard do CloudKit apenas informa o número de registros para cada tipo e você consegue ver os dados da sua própria conta, mas não dos outros.&lt;/p&gt;

&lt;p&gt;Para acessar o banco de dados privado do usuário, utilizamos a propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;privateCloudDatabase&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;public-database&quot;&gt;Public database&lt;/h3&gt;

&lt;p&gt;Este é o banco de dados público, onde você pode armazenar dados globais do seu app ou dados criados pelos usuários que devem ser acessíveis pelos outros usuários.&lt;/p&gt;

&lt;p&gt;Apesar do banco de dados ser público, é possível restringir quem tem acesso aos registros armazenados nele utilizando Security Roles, mas não falarei sobre elas neste artigo.&lt;/p&gt;

&lt;p&gt;Para acessar o banco de dados público, utilizamos a propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;publicCloudDatabase&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;shared-database&quot;&gt;Shared database&lt;/h3&gt;

&lt;p&gt;Este é o banco de dados de compartilhamento. Com o lançamento do iOS 10 e do macOS Sierra a Apple liberou também a função de compartilhamento do CloudKit, pela qual usuários podem compartilhar registros específicos nos seus bancos de dados privados com contatos, permitindo com que ambos vejam e editem os registros simultaneamente. O banco de dados compartilhado é usado para armazenar esses registros, mas seu app não irá lidar com ele diretamente.&lt;/p&gt;

&lt;h2 id=&quot;zone&quot;&gt;Zone&lt;/h2&gt;

&lt;p&gt;Uma zona dentro do CloudKit é como se fosse uma pasta onde você salva seus registros. Todo banco de dados do CloudKit tem uma zona padrão, a &lt;code class=&quot;highlighter-rouge&quot;&gt;Default Zone&lt;/code&gt;. Você pode utilizar a zona padrão ou criar zonas novas para organizar seus registros. Só é possível criar zonas no banco de dados privado, o banco de dados público só permite o uso da zona padrão.&lt;/p&gt;

&lt;p&gt;Algumas funcionalidades do CloudKit só são possíveis em zonas customizadas. Se você quiser salvar vários objetos relacionados ao mesmo tempo e precisa que a operação falhe caso algum deles não possa ser salvo, precisa usar uma zona customizada. O novo recurso de compartilhamento também requer a utilização de uma zona customizada.&lt;/p&gt;

&lt;p&gt;Zonas são representadas por objetos do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKZone&lt;/code&gt;.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Obtendo uma lista de zonas&lt;/h3&gt;

&lt;p&gt;Para listar a zonas disponíveis em um banco de dados, utilizamos o método &lt;code class=&quot;highlighter-rouge&quot;&gt;fetchAllRecordZones&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKDatabase&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/f27e48e6eda5bf53d993e67d3fbfaa92.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;record&quot;&gt;Record&lt;/h2&gt;

&lt;p&gt;Records são os registros que estão salvos no banco de dados do CloudKit. Registros são representados por objetos do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;, que são basicamente dicionários onde podemos adicionar as chaves que quisermos, que se tornarão campos nas “tabelas” do servidor.&lt;/p&gt;

&lt;p&gt;É importante ressaltar que, apesar do banco de dados do CloudKit ser schemaless (você não precisa definir os campos previamente), isso só é verdade no ambiente de desenvolvimento, após colocar seu app em produção você terá que fazer alterações no seu schema no dashboard ou através do seu app em ambiente de desenvolvimento e depois exportar essas alterações para o ambiente de produção.&lt;/p&gt;

&lt;h3 id=&quot;tipos-de-dados-aceitos&quot;&gt;Tipos de dados aceitos&lt;/h3&gt;

&lt;p&gt;Embora &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; seja basicamente um dicionário, não significa que possamos salvar qualquer tipo de dado no CloudKit. Estes são os tipos de dados que podemos colocar nas chaves de um &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt;: a Apple recomenda &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; para pequenas quantidades de texto&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;NSNumber&lt;/code&gt;: tipos numéricos do Swift são convertidos automaticamente&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Data&lt;/code&gt;: um exemplo de uso para um campo tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;Data&lt;/code&gt; seria armazenar objetos próprios, codificados usando &lt;code class=&quot;highlighter-rouge&quot;&gt;NSCoding&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Date&lt;/code&gt;: datas e horas podem ser armazenadas diretamente no CloudKit&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;CLLocation&lt;/code&gt;: muito útil para apps que trabalham com localização, até porque é possível fazer queries com base em localização (mais sobre isso depois)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt;: este objeto do CloudKit representa um arquivo que pode conter uma grande quantidade de dados (fotos e vídeos, por exemplo)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;CKReference&lt;/code&gt;: este objeto do CloudKit representa uma referência que aponta para outro &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; no banco de dados&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Além de poder utilizar os tipos citados acima por si só, qualquer chave em um &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; pode conter também um array desses tipos, desde que o array contenha objetos de um único tipo.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Criando um registro&lt;/h3&gt;

&lt;p&gt;Vamos supor que estamos criando um aplicativo onde usuários podem cadastrar filmes, provavelmente teríamos um registro chamado &lt;code class=&quot;highlighter-rouge&quot;&gt;Movie&lt;/code&gt;. Neste caso, &lt;code class=&quot;highlighter-rouge&quot;&gt;Movie&lt;/code&gt; é o nosso &lt;code class=&quot;highlighter-rouge&quot;&gt;recordType&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Para criar um registro de um filme, inicializamos um &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;record&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CKRecord&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;recordType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Movie&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Com o objeto criado, basta começar a setar as propriedades. Dentro do view controller do app onde o usuário entra com os dados do filme, poderíamos atualizar o record na action de um &lt;code class=&quot;highlighter-rouge&quot;&gt;UITextField&lt;/code&gt;, por exemplo:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/399eb8f10315b8c87ee1926e3ccd9807.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Agora você deve estar se perguntando: “o que diabos é &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecordValue&lt;/code&gt;? 🤔”.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecordValue&lt;/code&gt; é um protocolo adotado por objetos suportados pelo CloudKit. O problema é que, usando Swift, o compilador não compreende que &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; adota &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecordValue&lt;/code&gt; e por isso temos que fazer esse casting feio.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Melhorando nosso código: custom subscript&lt;/h3&gt;

&lt;p&gt;Para melhorar essa situação, sempre que trabalho com CloudKit eu crio enums com os campos dos meus registros e adiciono uma extensão em &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; com um custom subscript que aceita esse enum. Explicando assim parece complicado, mas no código é bem simples.&lt;/p&gt;

&lt;p&gt;Primeiro, o enum dos campos do nosso registro:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/a66fd48d4e27a737718e9ddcd3b10fb9.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Agora podemos criar a extensão em &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/7c862fa6226d8ecac72a4f137f699c46.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Agora, para modificar os valores dos nossos registros, nosso código fica bem mais limpo, podemos fazer simplesmente assim:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;record&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;title&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;title&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;record&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;releaseDate&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;date&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;record&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;rating&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;rating&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// e assim por diante...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Vale ressaltar que com este subscript customizado, continuamos só podendo colocar no nosso registro valores suportados pelo CloudKit. Se tentarmos colocar algum valor não suportado, o campo ficará nulo.&lt;/p&gt;

&lt;p&gt;Outro detalhe importante: &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; &lt;strong&gt;não&lt;/strong&gt; é um value type, então quando você passa objetos do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; você está passando uma referência e, caso tenha &lt;code class=&quot;highlighter-rouge&quot;&gt;didSet&lt;/code&gt; em propriedades do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;, o &lt;code class=&quot;highlighter-rouge&quot;&gt;didSet&lt;/code&gt; não será chamado quando algum campo do registro for alterado 😉&lt;/p&gt;

&lt;p&gt;Na “vida real”, você deve utilizar seus próprios models (provavelmente value types) e convertê-los de/para &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; quando estiver lidando com o CloudKit.&lt;/p&gt;

&lt;p style=&quot;background-color:#f5f5f5;border-left:5px solid #3461A6;padding:10px&quot;&gt;O código completo desta parte você encontra no &lt;a href=&quot;https://github.com/insidegui/CloudKitchenSink/blob/master/CloudKitchenSink/SimpleRecordTableViewController.swift&quot;&gt;arquivo SimpleRecordTableViewController.swift do projeto de exemplo&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;cloudkit-dashboard&quot;&gt;CloudKit Dashboard&lt;/h2&gt;

&lt;p&gt;Agora que já sabemos como criar registros no CloudKit, seria interessante termos uma forma de ver o que está acontecendo no servidor quando salvamos nossos registros.&lt;/p&gt;

&lt;p&gt;A Apple criou uma ferramenta para isto, o CloudKit Dashboard. No dashboard nós temos acesso a todos os nossos containers, bancos de dados, tipos de registros e muito mais.&lt;/p&gt;

&lt;p&gt;Primeiramente, usando o app de exemplo, vamos criar um registro:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/simple-record.gif&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Agora que temos um registro criado, vamos acessar o dashboard. O primeiro passo é selecionar no menu do canto superior esquerdo com qual container queremos trabalhar.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/dashboard-container-menu.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Com o container selecionado, vemos inicialmente uma lista dos tipos de registro que temos. Todo banco de dados do CloudKit já vem por padrão com um tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;User&lt;/code&gt;, que armazena informações sobre usuários.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/dashboard-record-types.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Para visualizarmos o registro salvo no banco de dados público, selecionamos a opção “Default Zone” em “Public Data”. Se tivéssemos outras zonas, elas apareceriam nesta mesma lista.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/dashboard-records.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Agora o dashboard está nos avisando que ele precisa de um index no ID do registro para fazer uma listagem deles. Basta clicar em “Add Record ID Query Index” e o dashboard irá então mostrar o registro que criamos usando o app.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/dashboard-records-2.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Note que, além dos dados que nós inserimos, o registro contém alguns metadados que o CloudKit adiciona automaticamente:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Record Name&lt;/code&gt;: este é o ID único do registro, usado para localizar registros no banco de dados. Nós podemos definir este ID ou deixar que o CloudKit defina um automaticamente, neste caso ele usa um &lt;code class=&quot;highlighter-rouge&quot;&gt;UUID&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Created&lt;/code&gt;: a data de criação do registro. Pode ser acessada através da propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;creationDate&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Created By&lt;/code&gt;: o ID do usuário que criou o registro. Pode ser acessado através da propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;creatorUserRecordID&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Modified&lt;/code&gt;: a data da última alteração do registro. Pode ser acessada através da propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;modificationDate&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Modified By&lt;/code&gt;: o ID do usuário que realizou a última alteração no registro. Pode ser acessado através da propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;lastModifiedUserRecordID&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;user-records&quot;&gt;User Records&lt;/h2&gt;

&lt;p&gt;Como vimos na seção sobre o dashboard, o CloudKit cria automaticamente registros para os usuários do nosso app. Esses registros são do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;User&lt;/code&gt; e contém por padrão somente um identificador único do usuário. Esse identificador é único por container, quer dizer que um usuário terá o mesmo identificador único em todos os bancos de dados e zonas dentro do seu container, mas se você utilizar mais de um container, verá IDs diferentes para o mesmo usuário em cada um deles.&lt;/p&gt;

&lt;p&gt;O CloudKit nos permite fazer diversas coisas com o registro do usuário:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Descobrir se o usuário está logado no iCloud ou não&lt;/li&gt;
  &lt;li&gt;Obter o registro do usuário no container&lt;/li&gt;
  &lt;li&gt;Obter o nome completo do usuário&lt;/li&gt;
  &lt;li&gt;Obter os identificadores dos contatos do usuário que possuem registros correspondentes no mesmo container&lt;/li&gt;
  &lt;li&gt;Atualizar o registro com dados úteis para o nosso app&lt;/li&gt;
  &lt;li&gt;Ser notificado de mudanças no status da conta do iCloud&lt;/li&gt;
&lt;/ul&gt;

&lt;p style=&quot;background-color:#f5f5f5;border-left:5px solid #3461A6;padding:10px&quot;&gt;Todos os exemplos desta parte você encontra na íntegra no &lt;a href=&quot;https://github.com/insidegui/CloudKitchenSink/blob/master/CloudKitchenSink/UserViewController.swift&quot;&gt;arquivo UserViewController.swift do projeto de exemplo&lt;/a&gt;.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Descobrindo se o usuário está logado&lt;/h3&gt;

&lt;p&gt;Em muitos casos é importante sabermos se o usuário está logado no iCloud no dispositivo atual para decidirmos se ativamos determinada funcionalidade do app ou até mesmo para impedir que o usuário utilize o app até que esteja logado.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Importante:&lt;/strong&gt; caso você decida não permitir com que o usuário utilize o app sem estar logado no iCloud, lembre-se que poderá ter que prestar esclarecimentos para o time de review da Apple, afinal eles não gostam de apps que exigem algum tipo de login sem uma boa justificativa. Seu app precisa ter um bom motivo para exigir o login, do contrário poderá ser rejeitado.&lt;/p&gt;

&lt;p&gt;Para obter o status da conta do iCloud, usamos o método &lt;code class=&quot;highlighter-rouge&quot;&gt;accountStatus&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/5523796b377133a637855e837acfbb7d.js&quot;&gt;&lt;/script&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Obtendo o ID do registro do usuário&lt;/h3&gt;

&lt;p&gt;Para obter o registro do usuário do CloudKit, primeiro precisamos saber o ID dele. Para isso, utilizamos o método &lt;code class=&quot;highlighter-rouge&quot;&gt;fetchUserRecordID&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/f0140a3255a6a033d84cf4417998b6f9.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;a name=&quot;user-record-fetch&quot;&gt;&lt;/a&gt;
Agora que nós temos um &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecordID&lt;/code&gt; referente ao registro do usuário, podemos usar o método &lt;code class=&quot;highlighter-rouge&quot;&gt;fetch&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKDatabase&lt;/code&gt; no banco de dados público para baixar o registro completo do usuário.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/42787a138c7213dd18e23b0ad633150c.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;No exemplo eu estou usando &lt;code class=&quot;highlighter-rouge&quot;&gt;publicCloudDatabase&lt;/code&gt;, mas poderia usar &lt;code class=&quot;highlighter-rouge&quot;&gt;privateCloudDatabase&lt;/code&gt;. Qual banco de dados usar aqui vai depender da sua aplicação, como o app de exemplo usa somente o banco de dados público, optei por usar este.&lt;/p&gt;

&lt;p&gt;É possível ter dois registros diferentes para o mesmo usuário: um no banco de dados público e outro no banco de dados privado, embora ambos tenham o mesmo identificador, os dados contidos em cada um deles podem ser diferentes. Você pode por exemplo utilizar o registro do usuário no banco de dados público para salvar informações como avatar e apelido e usar o registro no banco de dados privado para e-mail, endereço e outros dados sigilosos.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Obtendo o nome completo do usuário&lt;/h3&gt;

&lt;p&gt;Podemos obter o nome completo do usuário autenticado, mas isso requer a permissão do mesmo.&lt;/p&gt;

&lt;p&gt;Para solicitar essa permissão, utilizamos o método &lt;code class=&quot;highlighter-rouge&quot;&gt;requestApplicationPermission&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;, passando o parâmetro &lt;code class=&quot;highlighter-rouge&quot;&gt;.userDiscoverability&lt;/code&gt;. Aparecerá um alert para o usuário solicitando permissão.&lt;/p&gt;

&lt;p&gt;Após obtermos permissão, utilizamos o método &lt;code class=&quot;highlighter-rouge&quot;&gt;discoverUserIdentity&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt; para obter a identidade do usuário, que contém o seu nome completo na forma de &lt;code class=&quot;highlighter-rouge&quot;&gt;PersonNameComponents&lt;/code&gt; que podemos formatar através de um &lt;code class=&quot;highlighter-rouge&quot;&gt;PersonNameComponentsFormatter&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/4a282db0d8843b1503087f85fe8c3039.js&quot;&gt;&lt;/script&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Descobrindo contatos do usuário que utilizam o mesmo app&lt;/h3&gt;

&lt;p&gt;Para obter uma lista de registros dos amigos do usuário que utilizam o app, ou seja, que tem registro no mesmo container, utilizamos o método &lt;code class=&quot;highlighter-rouge&quot;&gt;discoverAllIdentities&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/63ad1684f37b2dc3701029d17d625313.js&quot;&gt;&lt;/script&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Inserindo dados adicionais no registro do usuário&lt;/h3&gt;

&lt;p&gt;No nosso app de exemplo, vamos supor que nós queremos listar os filmes cadastrados e junto ao filme exibir o nome e avatar do usuário que cadastrou aquele filme. Infelizmente a Apple não fornece uma opção para obter o avatar do usuário do iCloud, mas nós podemos oferecer esta funcionalidade no nosso próprio app, utilizando um campo no user record.&lt;/p&gt;

&lt;p&gt;Para isto, vamos aprender também sobre uma nova classe: &lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt; é um objeto usado para armazenar arquivos grandes no CloudKit. A Apple recomenda que qualquer campo que seja maior do que alguns kilobytes seja armazenado usando &lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Trabalhar com &lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt; é muito simples: basta inicializá-lo com a URL para um arquivo que queremos armazenar no CloudKit e apontar um campo de um &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt; para o &lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt; criado.&lt;/p&gt;

&lt;p&gt;Quando o registro for salvo, o CloudKit cuidará de enviar o arquivo junto dele. No caso do nosso app estamos enviando imagens para serem usadas como avatar, no meu código de exemplo não há nenhum tipo de tratamento quanto ao tipo de imagem ou tamanho do arquivo, mas se fosse um app real eu provavelmente iria validar e redimensionar a imagem para evitar desperdício de espaço no iCloud e consumo de banda desnecessário.&lt;/p&gt;

&lt;p&gt;Eu adicionei um botão na interface que abre um &lt;code class=&quot;highlighter-rouge&quot;&gt;UIImagePickerController&lt;/code&gt; para que o usuário possa selecionar uma foto da biblioteca para servir de avatar. O exemplo abaixo mostra a implementação do que acontece após o usuário selecionar uma imagem:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/8c960b15f65aa123fe9e20fe2ee07226.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;No exemplo acima, &lt;code class=&quot;highlighter-rouge&quot;&gt;imageURL&lt;/code&gt; é uma &lt;code class=&quot;highlighter-rouge&quot;&gt;URL&lt;/code&gt; para um arquivo salvo localmente, se você tentar inicializar um &lt;code class=&quot;highlighter-rouge&quot;&gt;CKAsset&lt;/code&gt; com algum outro tipo de &lt;code class=&quot;highlighter-rouge&quot;&gt;URL&lt;/code&gt; haverá uma exception e seu app irá travar.&lt;/p&gt;

&lt;p&gt;O método &lt;code class=&quot;highlighter-rouge&quot;&gt;save&lt;/code&gt; é usado tanto para criar quanto para atualizar registros. Ao passar um registro com um ID que já existe no servidor, o CloudKit irá atualizar por padrão apenas os campos que foram alterados desde o último salvamento.&lt;/p&gt;

&lt;p&gt;Como podem ver, é muito simples adicionar um campo personalizado ao registro do usuário e enviar arquivos para o CloudKit.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/avatar.gif&quot; /&gt;&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Observando mudanças no status da conta do iCloud&lt;/h3&gt;

&lt;p&gt;Algo que pode acontecer enquanto seu app está rodando é que o usuário pode abrir as preferências do iCloud e trocar de conta, não estar logado e então logar ou estar logado e fazer logoff.&lt;/p&gt;

&lt;p&gt;Em qualquer um desses casos, se o seu app varia de acordo com a conta do iCloud ativa, você precisa atualizar o estado do app para refletir esta mudança.&lt;/p&gt;

&lt;p&gt;Para ser notificado de mudanças na conta do iCloud, basta registrar um observer para a notificação &lt;code class=&quot;highlighter-rouge&quot;&gt;.CKAccountChanged&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/0868e826fb781a07958963802c069e44.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;No meu exemplo, ao receber esta notificação, estou chamando o método do view controller que faz o processo de descoberta de todos os dados do usuário. Assim, a interface ficará sempre em sincronia com o status do iCloud no dispositivo.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/account.gif&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;queries&quot;&gt;Queries&lt;/h2&gt;

&lt;p&gt;Agora que já vimos como salvar informações no CloudKit, vamos ver como fazemos para buscar essas informações. A forma mais simples de obter um registro do CloudKit é através de uma simples busca com base em um ID, &lt;a href=&quot;#user-record-fetch&quot;&gt;como já vimos antes&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Se quisermos fazer buscas mais avançadas, filtradas com base em outros campos do registro, precisaremos utilizar a classe &lt;code class=&quot;highlighter-rouge&quot;&gt;CKQuery&lt;/code&gt;. Com ela, podemos especificar um predicate que irá definir um filtro para a busca.&lt;/p&gt;

&lt;p&gt;Se você não tem familiaridade com &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt;, recomendo que &lt;a href=&quot;https://developer.apple.com/reference/foundation/nspredicate&quot;&gt;dê uma lida na documentação&lt;/a&gt;, pois trata-se de uma classe muito poderosa e que é usada em diversas APIs da Apple.&lt;/p&gt;

&lt;p&gt;Para rodarmos uma query no CloudKit, iremos utilizar uma &lt;code class=&quot;highlighter-rouge&quot;&gt;CKQueryOperation&lt;/code&gt;. Realizar queries é apenas uma dentre muitas funcionalidades do CloudKit que são expostas na forma de operations.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Obtendo todos os registros de um determinado tipo&lt;/h3&gt;

&lt;p&gt;Este é o exemplo mais simples. Vamos executar uma query para obter todos os filmes que temos registrados no nosso banco de dados público. O primeiro passo é construir uma query com um tipo de registro e um predicate, como queremos todos os registros, basta criarmos uma query especificando o tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;Movie&lt;/code&gt; e um predicate com o valor &lt;code class=&quot;highlighter-rouge&quot;&gt;true&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/839813b1754e31b648aaf47c50ae636a.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Agora que temos uma operação, antes de executá-la, precisamos definir os callbacks que serão chamados para que sejamos informados de novos resultados e possíveis erros na operação:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/c3338649c87ae8535294dfa710532928.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;CKQueryOperation&lt;/code&gt; tem dois callbacks: um que é chamado para cada registro obtido do CloudKit e outro que é chamado no final da operação, após todos os registros terem sido baixados.&lt;/p&gt;

&lt;p&gt;Há dois parâmetros neste último callback que merecem comentário: &lt;code class=&quot;highlighter-rouge&quot;&gt;cursor&lt;/code&gt; é um objeto do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKCursor&lt;/code&gt; que poderá estar presente ao final da operação caso haja mais resultados a serem obtidos. Se sua query for retornar uma quantidade muito grande de registros, você terá que executar várias &lt;code class=&quot;highlighter-rouge&quot;&gt;CKQueryOperation&lt;/code&gt;s para conseguir obter todos eles, passando o &lt;code class=&quot;highlighter-rouge&quot;&gt;cursor&lt;/code&gt; nas queries subsequentes.&lt;/p&gt;

&lt;p&gt;O parâmetro &lt;code class=&quot;highlighter-rouge&quot;&gt;error&lt;/code&gt; também é importantíssimo, a partir dele é possível saber se houve um erro na operação e qual a natureza do erro. Alguns erros no CloudKit são recuperáveis, isso significa que não basta simplesmente exibir um alerta ao usuário no primeiro erro encontrado, você precisa lidar com o erro. Dependendo de qual foi o erro, o CloudKit irá informar até mesmo em quantos segundos é recomendado que a operação seja tentada novamente (e você deve definitivamente seguir essa recomendação).&lt;/p&gt;

&lt;p&gt;Finalmente, após configurarmos nossa operação, basta executá-la, adicionando-a ao banco de dados:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/e2834c0cb17d19a405a538ef2829683b.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Se quiséssemos executar a operação no banco de dados privado, bastaria substituir &lt;code class=&quot;highlighter-rouge&quot;&gt;publicCloudDatabase&lt;/code&gt; por &lt;code class=&quot;highlighter-rouge&quot;&gt;privateCloudDatabase&lt;/code&gt;. Existem algumas outras operações do CloudKit que são executadas no nível do container, nesses casos você chamaria o método &lt;code class=&quot;highlighter-rouge&quot;&gt;add&lt;/code&gt; de &lt;code class=&quot;highlighter-rouge&quot;&gt;CKContainer&lt;/code&gt;.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Realizando uma busca textual&lt;/h3&gt;

&lt;p&gt;Outro tipo de query muito comum de se fazer é a busca textual. No nosso exemplo, usuários podem querer buscar filmes pelo título. Felizmente o CloudKit sabe lidar muito bem com isso e podemos construir um predicate simples que dá conta do recado:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/5806c2078648de7425b1e59d6d2c49fb.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;O predicate &lt;code class=&quot;highlighter-rouge&quot;&gt;self contains %@&lt;/code&gt; significa “busque este valor em todos os parâmetros do registro que contenham texto”.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Realizando uma busca por localização geográfica&lt;/h3&gt;

&lt;p&gt;Parece mesmo que a Apple pensou em tudo, afinal podemos fazer até mesmo queries baseadas em localização usando o CloudKit. No meu exemplo utilizei a localização atual do dispositivo para buscar filmes que tenham sido gravados em locações num raio de 500km.&lt;/p&gt;

&lt;p&gt;Para fazermos uma query baseada em localização, o predicate fica desta forma:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/23d254910cc315d70143db0f8dfd232d.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Onde &lt;code class=&quot;highlighter-rouge&quot;&gt;location&lt;/code&gt; dentro da string se refere à chave no nosso registro, &lt;code class=&quot;highlighter-rouge&quot;&gt;currentLocation&lt;/code&gt; é um objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;CLLocation&lt;/code&gt; com a localização atual e &lt;code class=&quot;highlighter-rouge&quot;&gt;radius&lt;/code&gt; é um &lt;code class=&quot;highlighter-rouge&quot;&gt;Float&lt;/code&gt; contendo o tamanho do raio incluído na pesquisa (em quilômetros).&lt;/p&gt;

&lt;p&gt;Aqui está uma demonstração dos três tipos de query explicados acima:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/queries.gif&quot; /&gt;&lt;/p&gt;

&lt;p style=&quot;background-color:#f5f5f5;border-left:5px solid #3461A6;padding:10px&quot;&gt;O código completo desta parte você encontra no &lt;a href=&quot;https://github.com/insidegui/CloudKitchenSink/blob/master/CloudKitchenSink/QueryTableViewController.swift&quot;&gt;arquivo QueryTableViewController.swift do projeto de exemplo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Fazer queries no banco de dados nos dá total flexibilidade para obtermos apenas as informações mais relevantes ao contexto do nosso app, mas o CloudKit tem algo ainda mais legal que isso. Com ele nós podemos criar queries persistentes, executadas a cada alteração no banco de dados e que notificam nosso app via push. Essas queries persistentes são chamadas de subscriptions.&lt;/p&gt;

&lt;h2 id=&quot;subscriptions&quot;&gt;Subscriptions&lt;/h2&gt;

&lt;p&gt;Lembram que eu falei anteriormente sobre enviar notificações usando o CloudKit? É exatamente isso que subscriptions nos permitem fazer.&lt;/p&gt;

&lt;p&gt;Através de subscriptions, nós registramos o interesse de um determinado dispositivo ser notificado toda vez que alguma alteração ocorrer no banco de dados. Então, se um novo registro for inserido, o CloudKit irá enviar uma notificação para aquele dispositivo. Essas notificações podem ser apenas de &lt;code class=&quot;highlighter-rouge&quot;&gt;content-available&lt;/code&gt; (silenciosas), ou notificações normais que mostram um alerta no dispositivo e/ou colocam números no badge do app.&lt;/p&gt;

&lt;p&gt;Através de notificações silenciosas, podemos garantir um update imediato em todos os dispositivos do usuário sempre que o mesmo fizer alguma alteração em outro dispositivo, afinal este tipo de notificação dá ao nosso app a oportunidade de efetuar um background fetch.&lt;/p&gt;

&lt;h3 style=&quot;color:#C86D6C&quot;&gt;Criando subscription para envio de notificações&lt;/h3&gt;

&lt;p&gt;Para criar uma subscription que envia notificações, primeiro precisamos obter permissão do usuário para que ele receba as notificações do nosso app e dizer para o sistema que queremos utilizar notificações remotas.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/d9510bb2b567b3f01552bfd303fa0a04.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Se você for usar somente notificações silenciosas (&lt;code class=&quot;highlighter-rouge&quot;&gt;content-available&lt;/code&gt;), só precisa fazer a última chamada (&lt;code class=&quot;highlighter-rouge&quot;&gt;registerForRemoteNotifications&lt;/code&gt;). No app de exemplo estamos usando notificações de alerta com som, por isso precisamos solicitar permissão através do &lt;code class=&quot;highlighter-rouge&quot;&gt;UNUserNotificationCenter&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Tendo permissão do usuário para enviar notificações, podemos criar nossa subscription com o CloudKit. A subscription é um objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;CKSubscription&lt;/code&gt;, que criamos desta forma:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/3228e3d30cd257f3cc2b27dfc824016d.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Vamos ver o que cada coisa significa:&lt;/p&gt;

&lt;h4 id=&quot;recordtype&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;recordType&lt;/code&gt;&lt;/h4&gt;

&lt;p&gt;O tipo de registro para o qual queremos receber notificações.&lt;/p&gt;

&lt;h4 id=&quot;predicate&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;predicate&lt;/code&gt;&lt;/h4&gt;

&lt;p&gt;Qual query será executada para determinar se uma notificação será disparada ou não (neste exemplo, qualquer registro). Como mencionei na parte anterior, subscriptions são como queries persistentes que ficam rodando no servidor a cada alteração no banco de dados, é através deste parâmetro que nós determinamos que query será essa.&lt;/p&gt;

&lt;p&gt;Lembram da query com localização que fizemos no exemplo anterior? Poderíamos registrar uma subscription com aquela query, fazendo com que o usuário seja notificado sempre que um filme gravado perto da sua cidade for registrado no sistema.&lt;/p&gt;

&lt;h4 id=&quot;options&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;options&lt;/code&gt;&lt;/h4&gt;

&lt;p&gt;Uma lista definindo em quais circunstâncias a notificação será disparada. Podemos pedir para que a notificação seja disparada quando um novo registro for criado, um registro existente for alterado ou excluído (ou as três opções ao mesmo tempo).&lt;/p&gt;

&lt;h4 style=&quot;color:#C86D6C&quot;&gt;Definindo como será a notificação&lt;/h4&gt;

&lt;p&gt;Com nossa subscription criada, precisamos definir como será a notificação que essa subscription irá gerar. Para isso, vamos criar um objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;CKNotificationInfo&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/d607ab29d2c60ddb6b297d51bbfa1265.js&quot;&gt;&lt;/script&gt;

&lt;h4 id=&quot;alertlocalizationkey&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;alertLocalizationKey&lt;/code&gt;&lt;/h4&gt;

&lt;p&gt;Este parâmetro é uma chave no nosso &lt;code class=&quot;highlighter-rouge&quot;&gt;Localizable.strings&lt;/code&gt; que será o formato do alerta. É necessário usar este parâmetro quando você precisa incluir dados do registro no texto do alerta. No meu caso eu estou incluindo o título do filme que foi criado:&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;&quot;movie_registered_alert&quot; = &quot;%@ has been registered, check it out!&quot;;&lt;/code&gt;&lt;/p&gt;

&lt;h4 id=&quot;alertlocalizationargs&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;alertLocalizationArgs&lt;/code&gt;&lt;/h4&gt;

&lt;p&gt;As chaves do registro que serão usadas para popular os placeholders no texto do alerta. No exemplo estou usando a chave &lt;code class=&quot;highlighter-rouge&quot;&gt;title&lt;/code&gt;, que é o título do filme.&lt;/p&gt;

&lt;h4 id=&quot;desiredkeys&quot;&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;desiredKeys&lt;/code&gt;&lt;/h4&gt;

&lt;p&gt;As chaves do registro que serão enviadas junto da notificação, que podemos usar no app para fazer uma query e localizar o registro.&lt;/p&gt;

&lt;h4 style=&quot;color:#C86D6C&quot;&gt;Salvando a subscription&lt;/h4&gt;

&lt;p&gt;Agora que criamos a subscription e definimos como serão as notificações, basta salvá-la como se fosse um registro qualquer:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/84c92632f108899c84e1de8d56df9654.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Lembrando que a subscription deverá ser salva no banco de dados para o qual você deseja ser notificado. Como o app de exemplo usa o banco de dados público, estou usando &lt;code class=&quot;highlighter-rouge&quot;&gt;publicCloudDatabase&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Com a configuração acima, ao criar um registro em outro dispositivo, meu iPhone e meu Apple Watch receberam a seguinte notificação:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/notification_watch.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/notification_phone.png&quot; /&gt;&lt;/p&gt;

&lt;p style=&quot;background-color:#f5f5f5;border-left:5px solid #3461A6;padding:10px&quot;&gt;O código completo desta parte você encontra no &lt;a href=&quot;https://github.com/insidegui/CloudKitchenSink/blob/master/CloudKitchenSink/SubscriptionViewController.swift&quot;&gt;arquivo SubscriptionViewController.swift do projeto de exemplo&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;arquitetura-para-sincronização&quot;&gt;Arquitetura para sincronização&lt;/h1&gt;

&lt;p&gt;O que nós vimos até agora no artigo foram apenas os conceitos básicos de como utilizar as funcionalidades do CloudKit. Para criar um app que sincroniza de forma eficiente e correta os dados do usuário, há muito mais a ser feito.&lt;/p&gt;

&lt;p&gt;Para tentar ajudar quem precisa dessa funcionalidade, criei um simples app para criação de notas (estilo Notes da Apple) que usa uma arquitetura offline-first para sincronização.&lt;/p&gt;

&lt;p&gt;O fluxo do app é mais ou menos assim:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/img/insidegui/cloudkit/sync_flow.gif&quot; /&gt;&lt;/p&gt;

&lt;p&gt;As notas são salvas localmente num banco de dados &lt;a href=&quot;https://realm.io&quot;&gt;Realm&lt;/a&gt;. Através de &lt;a href=&quot;https://realm.io/docs/swift/latest/#notifications&quot;&gt;Realm Notifications&lt;/a&gt;, o motor de sincronização sabe sempre que uma nota é adicionada, alterada ou removida no banco de dados local. Essas alterações são reconhecidas pelo motor de sincronização, que transforma os models em &lt;code class=&quot;highlighter-rouge&quot;&gt;CKRecord&lt;/code&gt;s e envia para o CloudKit.&lt;/p&gt;

&lt;p&gt;O mesmo processo acontece inverso quando a alteração ocorre no CloudKit: o app recebe uma notificação remota, pega as informações sobre quais registros foram adicionados/alterados/removidos e replica essas alterações no banco de dados local. A alteração no banco de dados local causa um update na interface.&lt;/p&gt;

&lt;p&gt;Um cuidado que precisa ser tomado neste caso é no sentido de evitar loops de sincronização. Se uma alteração no Realm provoca um salvamento no CloudKit e uma alteração no CloudKit provoca um download e alteração no Realm, temos um loop. Para evitar este problema, o motor de sincronização registra um notification token com o Realm para que as alterações provocadas por ele não façam com que as notificações sejam enviadas para ele mesmo.&lt;/p&gt;

&lt;h2 id=&quot;tratamento-de-erros&quot;&gt;Tratamento de erros&lt;/h2&gt;

&lt;p&gt;É muito importante observar a ocorrência de erros nas operações do CloudKit e tentar lidar com eles da melhor forma possível. Muitos desenvolvedores estão acostumados a simplesmente colocar um &lt;code class=&quot;highlighter-rouge&quot;&gt;print&lt;/code&gt; quando ocorre um erro ou mostrar um alerta para o usuário, mas nem sempre esta é a melhor alternativa.&lt;/p&gt;

&lt;p&gt;A primeira coisa que você deve fazer é verificar se o erro é recuperável. Existem dois casos muito comuns que causam erros recuperáveis quando estamos trabalhando com CloudKit:&lt;/p&gt;

&lt;h3 id=&quot;erro-temporário--timeout--internet-ruim--rate-limit&quot;&gt;Erro temporário / timeout / internet ruim / rate limit&lt;/h3&gt;

&lt;p&gt;Às vezes pode ocorrer um pequeno &lt;em&gt;glitch&lt;/em&gt; na conexão ou nos servidores da Apple que causa um erro temporário. Também pode acontecer do seu app estar chamando o CloudKit com muita frequência, neste caso o servidor irá recusar alguns requests para aliviar o excesso de carga. Nesses casos, o &lt;code class=&quot;highlighter-rouge&quot;&gt;error&lt;/code&gt; retornado no callback da operação será do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;CKError&lt;/code&gt;, que contém uma propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;retryAfterSeconds&lt;/code&gt;. Se esta propriedade não for &lt;code class=&quot;highlighter-rouge&quot;&gt;nil&lt;/code&gt;, use o valor contido nela como um delay para tentar novamente a operação que falhou.&lt;/p&gt;

&lt;p&gt;Nos meus projetos com CloudKit eu sempre tenho uma função mais ou menos assim:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/insidegui/8c726b4b705ddfe2fe01f24672c9a792.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Esta função facilita o tratamento de erros recuperáveis do CloudKit. Ela recebe um erro retornado de uma operação do CloudKit, um bloco a ser executado caso o erro seja recuperável e retorna um erro caso a operação não possa ser tentada novamente.&lt;/p&gt;

&lt;h3 id=&quot;conflitos&quot;&gt;Conflitos&lt;/h3&gt;

&lt;p&gt;Outro caso que pode acontecer é um conflito entre duas alterações no banco de dados. O usuário pode ter modificado um registro em um dispositivo enquanto o mesmo estava offline e depois fez uma alteração diferente em outro dispositivo. Neste caso, o salvamento irá falhar e o CloudKit irá retornar um erro do tipo &lt;code class=&quot;highlighter-rouge&quot;&gt;server​Record​Changed&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;O &lt;code class=&quot;highlighter-rouge&quot;&gt;userInfo&lt;/code&gt; desse erro irá conter o registro original antes da modificação, o registro atual no servidor e o registro atual no cliente. Com estas informações, cabe ao seu app decidir o que fazer para solucionar o conflito. Alguns apps exibem um painel para que o usuário decida o que fazer, outros fazem um merge do conteúdo automaticamente e outros apenas salvam o registro que foi modificado mais recentemente.&lt;/p&gt;

&lt;p style=&quot;background-color:#f5f5f5;border-left:5px solid #3461A6;padding:10px&quot;&gt;O código completo desta parte você encontra no &lt;a href=&quot;https://github.com/insidegui/NoteTaker&quot;&gt;projeto NoteTaker, no meu Github&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;conclusão&quot;&gt;Conclusão&lt;/h1&gt;

&lt;p&gt;Com isto, chegamos ao fim deste &lt;strike&gt;pequeno&lt;/strike&gt; artigo sobre CloudKit. Espero que este artigo tenha te ajudado a entender melhor o que é o CloudKit e tenha te dado ideias de como poderá utilizá-lo em seus projetos.&lt;/p&gt;

&lt;h1 id=&quot;sugestões-de-estudo&quot;&gt;Sugestões de estudo&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/reference/cloudkit&quot;&gt;Documentação da Apple sobre o CloudKit&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/library/content/documentation/General/Conceptual/iCloudDesignGuide/DesigningforCloudKit/DesigningforCloudKit.html&quot;&gt;Designing for CloudKit&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://medium.com/@kwylez/cloudkit-sharing-series-creating-the-ckshare-40e420b94ee8#.7snggpqs1&quot;&gt;CloudKit Sharing&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://developer.apple.com/search/?type=Videos&amp;amp;q=CloudKit&quot;&gt;Todas as sessions da WWDC sobre CloudKit&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Guilherme Rambo</name></author><category term="cloudkit" /><summary type="html">Guilherme Rambo (@_inside) é desenvolvedor iOS na Peixe Urbano, criador do BrowserFreedom, ChibiStudio e criador de diversos projetos open-source, incluindo o app da WWDC para macOS.</summary></entry><entry><title type="html">Swift &amp;amp; Machine Learning</title><link href="http://equinocios.com/tutorial/2017/03/23/swift-machine-learning/" rel="alternate" type="text/html" title="Swift &amp; Machine Learning" /><published>2017-03-23T00:10:00+00:00</published><updated>2017-03-23T00:10:00+00:00</updated><id>http://equinocios.com/tutorial/2017/03/23/swift-machine-learning</id><content type="html" xml:base="http://equinocios.com/tutorial/2017/03/23/swift-machine-learning/">&lt;blockquote&gt;
  &lt;p&gt;Geralmente, quando se fala em aprendizado de máquina para mobile, é mais comum ver códigos escritos em Python ou R, rodando do lado do servidor. No entanto, há casos em que compensa mais fazer o processamento localmente (por poder ser feito offline, e não sobrecarregar o server). Por isso o uso de Swift é justificável. Uns 4 anos atrás, eu falaria pra usar o OpenCV rodando nativo em C++, mas os tempos são outros.&lt;/p&gt;

  &lt;p&gt;Se você, caro leitor, nunca teve contato com inteligência artificial, não tema; este artigo não assume que você conheça previamente nada sobre.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;resumo&quot;&gt;Resumo&lt;/h3&gt;

    &lt;p&gt;Vamos juntos, neste artigo, estudar a base de dados sobre Recursos Humanos do &lt;em&gt;Kaggle&lt;/em&gt;, e criar uma nova implementação do algoritmo Random Forest na linguagem &lt;em&gt;Swift&lt;/em&gt;. Em termos da linguagem &lt;em&gt;Swift&lt;/em&gt;, discutiremos &lt;em&gt;generics&lt;/em&gt;, ponteiros e paralelização. De Aprendizado de Máquina, vamos falar de engenharia de features, dados, parâmetros e validação. Sobre engenharia de algoritmos, vamos ver complexidade, otimização e estruturas de dados.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;introdução&quot;&gt;Introdução&lt;/h3&gt;

    &lt;p&gt;Em termos de frameworks para ML (&lt;em&gt;machine learning&lt;/em&gt;), o Swift não está muito bem. Existem &lt;a href=&quot;https://github.com/josephmisiti/awesome-machine-learning#swift-general-purpose&quot;&gt;alguns projetos&lt;/a&gt; isolados, mas todos são promessas inacabadas, e nenhum tinha o algoritmo que eu queria usar (&lt;em&gt;Random Forest&lt;/em&gt;). Logo, como eu não queria incentivar o &lt;em&gt;black-box&lt;/em&gt; &lt;a href=&quot;http://www.ic.unicamp.br/~rocha/pub/papers/2010-sibgrapi-ml-black-boxes.pdf&quot;&gt;que já rola na área&lt;/a&gt;, surgiu este artigo: escrever o algoritmo. Eu não tenho como ressaltar isso o suficiente:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;E S C R E V A      S E U S      A L G O R I T M O S&lt;/p&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Pra quem quer se aprofundar na área, recomento o livro clássico &lt;a href=&quot;http://aima.cs.berkeley.edu/&quot;&gt;Inteligência Artificial: uma abordagem moderna&lt;/a&gt; e o &lt;a href=&quot;https://www.coursera.org/learn/machine-learning&quot;&gt;curso de Stanford&lt;/a&gt; (os dois rolavam soltos em pendrives quando eu cursei essa disciplina na universidade).&lt;/p&gt;

    &lt;p&gt;Neste artigo, vamos falar sobre Recursos Humanos, e como identificar funcionários que vão pedir demissão.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;sobre-homens-e-dados&quot;&gt;Sobre homens e dados&lt;/h3&gt;

    &lt;p&gt;Primeiramente, vamos falar dos nossos dados. A &lt;a href=&quot;https://www.kaggle.com/ludobenistant/hr-analytics&quot;&gt;base de recursos humanos&lt;/a&gt; é atualmente (Fev. 2017) a terceira mais votada no Kaggle. Ela tem um sutil &lt;em&gt;disclaimer&lt;/em&gt;: &lt;code class=&quot;highlighter-rouge&quot;&gt;This dataset is simulated&lt;/code&gt;. Logo, qualquer informação que tirarmos daqui não deve ser levada muito a sério.&lt;/p&gt;

    &lt;p&gt;Antes de qualquer coisa, vamos dar uma limpada na base de dados, uma &lt;em&gt;engenharia de features&lt;/em&gt;. Isso geralmente consiste em descartar dados menos relevantes, e realizar operações nos dados restantes.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;Um exemplo maravilhoso de engenharia de &lt;em&gt;features&lt;/em&gt; está &lt;a href=&quot;https://www.kaggle.com/c/titanic&quot;&gt;nos dados dos passageiros do Titanic&lt;/a&gt;. Ao correlacionar as entradas com a saída, o fator &lt;code class=&quot;highlighter-rouge&quot;&gt;sobreviveu? Sim ou não&lt;/code&gt;, vemos que as três informações claramente mais importantes são [Idade, Sexo, Classe]. Mulhers com mais de trinta anos, meninos com menos de dez anos, e passageiros da primeira classe, tem muito mais chances de sobreviver. Todavia, olhando cuidadosamente os nomes dos passageiros, podemos extrair o título dele (ex: Mr., Miss., Mrs.) que se torna uma feature poderosíssima.&lt;/p&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Escrevi um pequeno trecho de código em &lt;code class=&quot;highlighter-rouge&quot;&gt;Python&lt;/code&gt; pra fazer esse trabalho por nós:&lt;/p&gt;

    &lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c&quot;&gt;#!/usr/bin/env python&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pd&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read_csv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'HR.csv'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;drop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;columns&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;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&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;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&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;c&quot;&gt;#kill uninteresting rows&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;drop_duplicates&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;to_csv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'database.csv'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;As colunas &lt;code class=&quot;highlighter-rouge&quot;&gt;[Satisfação do funcionário, acidentes no trabalho, se foram promovidos recentemente, departamento, salário]&lt;/code&gt; contém os dados menos &lt;a href=&quot;http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.corr.html&quot;&gt;correlacionados&lt;/a&gt; com a saída dos funcionários. Isso nos deixa com os seguintes:&lt;/p&gt;

    &lt;table&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th&gt;Variável&lt;/th&gt;
          &lt;th&gt;Correlação com Y&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Anos na empresa&lt;/td&gt;
          &lt;td&gt;0.144822&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Média de horas por mês&lt;/td&gt;
          &lt;td&gt;0.071287&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Número de projetos realizados&lt;/td&gt;
          &lt;td&gt;0.023787&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Última avaliação do funcionário pela empresa&lt;/td&gt;
          &lt;td&gt;0.006567&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;florestal-randômico&quot;&gt;‘Florestal Randômico’&lt;/h3&gt;

    &lt;p&gt;O algoritmo &lt;em&gt;Random Forest&lt;/em&gt;, ou como eu o apelido carinhosamente, &lt;em&gt;Mata Atlântica&lt;/em&gt;, é um classificador supervisionado. Em outras palavras, ele divide dados em classes, e precisa saber previamente a classe dos seus dados para aprender a classificar outros. &lt;em&gt;Classe&lt;/em&gt; é o tipo do dado, no nosso caso, se o funcionário pediu ou não demissão.&lt;/p&gt;

    &lt;p&gt;Em termos simples, ele cria múltiplas &lt;a href=&quot;https://en.wikipedia.org/wiki/Decision_tree&quot;&gt;árvores de decisão&lt;/a&gt;, só que cada árvore usa um subconjunto aleatório de &lt;em&gt;features&lt;/em&gt;, e depois usamos &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Bootstrap_aggregating&quot;&gt;BAgging&lt;/a&gt;&lt;/em&gt; para decidir entre as árvores. Uma verdadeira sacada (&lt;em&gt;migué&lt;/em&gt;) que performa, pasme, impressionantemente bem e rápido. Na nossa implementação, vamos dar suporte aos seguintes parâmetros:&lt;/p&gt;

    &lt;table&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th&gt;Nome&lt;/th&gt;
          &lt;th&gt;Tipo&lt;/th&gt;
          &lt;th&gt;Descrição&lt;/th&gt;
          &lt;th&gt;Padrão&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Profundidade Máxima&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt; (1,∞)&lt;/td&gt;
          &lt;td&gt;Altura máxima de cada árvore, ou seja, máxima distância entre a raiz e as folhas. Aumentar esse número deixa o algoritmo mais rápido e menos preciso&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;10&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Tamanho Mínimo do Nó&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt; (1,∞)&lt;/td&gt;
          &lt;td&gt;Tamanho mínimo do subconjunto do &lt;code class=&quot;highlighter-rouge&quot;&gt;dataset&lt;/code&gt; no qual cada nó é dividido. Aumentar esse número deixa o algoritmo mais rápido e menos preciso&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;50&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Tamanho de &lt;code class=&quot;highlighter-rouge&quot;&gt;Sample&lt;/code&gt;&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt;(0,1)&lt;/td&gt;
          &lt;td&gt;Porcentagem do &lt;code class=&quot;highlighter-rouge&quot;&gt;dataset&lt;/code&gt; a ser &lt;em&gt;“sampleada”&lt;/em&gt; em cada árvore. Ajuda a deixar cada árvore diferente entre si&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;0.1&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Número de Árvores&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt;(1,∞)&lt;/td&gt;
          &lt;td&gt;Número de árvores construídas&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;10&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;em&gt;Seed&lt;/em&gt;&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt;&lt;/td&gt;
          &lt;td&gt;Semente do gerador de números aleatórios&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;&quot;Seed&quot;&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Tipo de Split&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;[All, Sqrt, Log2]&lt;/code&gt;&lt;/td&gt;
          &lt;td&gt;Número de features usado em cada split. Ajuda a deixar cada árvore diferente entre si&lt;/td&gt;
          &lt;td&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Sqrt&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;p&gt;Árvores diferentes entre si são o charme do &lt;code class=&quot;highlighter-rouge&quot;&gt;Random Forest&lt;/code&gt;. Vamos entender isso logo. Eis o pseudo-código que vamos implementar:&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;randomForest:
  Seja D o nosso dataset
  Para cada árvore a ser construída:
      seja S um subconjunto de D
      seja A(S) uma raiz de árvore
      A.M = obterSplit ( A )
      split ( A )

obterSplit ( Raiz de árvore A ):
	seja M o melhor split encontrado até o momento
	para cada feature F do split:
		para cada F[N] a feature de cada linha N de A.S:
			seja D,E subconjuntos de A.S
			para cada G[N] a feature de cada linha N de A.S:
				se G[N]&amp;gt;F[N] adicione G[N] a D
				caso contrário adicione a E
			se M'(D,E) for um split melhor que M, M recebe M'(D,E)
	retorna M

split  ( Nó de árvore A ):
	Se a direita, ou esqurerda do split de A for vazia, retorne nó folha (A.M)
	Se chegamos na profundidade máxima da árvore, retorne nó folha (A.M)
	Se a esquerda do split for menor que o tamanho mínimo:
		A.Nó_Esquerda = nó folha (A.M.E)
	Caso contrário:
		A.Nó_Esquerda = obterSplit(A.M.E)
		split (A.Nó_Esquerda)
	Se a direita do split for menor que o tamanho mínimo:
		A.Nó_Direita = nó folha (A.M.D)
	Caso contrário:
		A.Nó_Direita = obterSplit(A.M.D)
		split (A.Nó_Direita)
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;Qual é a complexidade deste algoritmo? Digamos que &lt;code class=&quot;highlighter-rouge&quot;&gt;L&lt;/code&gt; é o número de linhas do dataset, &lt;code class=&quot;highlighter-rouge&quot;&gt;C&lt;/code&gt; o total de &lt;em&gt;features&lt;/em&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;K&lt;/code&gt; o número de classes diferentes, e  &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt; o total de árvores construídas. Supondo que para determinar se um &lt;em&gt;Split&lt;/em&gt; é melhor do que outro, usamos o &lt;a href=&quot;https://en.wikipedia.org/wiki/Gini_coefficient&quot;&gt;&lt;em&gt;coeficiente Gini&lt;/em&gt;&lt;/a&gt;, que tem complexidade &lt;code class=&quot;highlighter-rouge&quot;&gt;O(L * K)&lt;/code&gt;, a complexidade do algoritmo seria:&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Compl. de construir a árvore: N log( N )
Compl. de cada nó: C * L * ( L + L * K ) ≃ C * L² * K
Resultado: O(CL²K log( CL²K ))
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;Note que estamos olhando de maneira quadrática pro &lt;em&gt;dataset&lt;/em&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;implementação-em-swift&quot;&gt;Implementação em Swift&lt;/h3&gt;

    &lt;h4 id=&quot;51-arrays-vs-ponteiros&quot;&gt;5.1 Arrays vs Ponteiros&lt;/h4&gt;

    &lt;p&gt;A estrutura de dados &lt;code class=&quot;highlighter-rouge&quot;&gt;Array&lt;/code&gt;, em Swift é muito conveniente, mas muito lenta. Vamos fazer um &lt;em&gt;benchmark&lt;/em&gt;?&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;let bm = BenchmarkTest.init(count: 1000000)
bm.begin()
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;Vamos conferir os números de acesso:&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Array Access: 			0.0430499911308289 s
NSMutableArray Access: 	0.519761979579926 s
Pointer Access: 		0.0407860279083252 s
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;E os tempos de &lt;em&gt;alloc/dealloc&lt;/em&gt;:&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Array Alloc: 				0.01119 s
NSMutableArray Alloc: 		2.32907 s
UnsafeMutablePointer Alloc: 0.00043 s
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;Claro que usando ponteiros INSEGUROS, temos que tomar conta da nossa própria memória. Mas o ganho de desempenho deve compensar esse preço. Como usar arrays de ponteiros? Vamos ver:&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;language-Swift&quot;&gt;// Em vez disso
let a:Array&amp;lt;Int&amp;gt; = Array(repeating:Int(0), count:10)
// faremos isso
let b:UnsafeMutablePointer&amp;lt;Int&amp;gt; = UnsafeMutablePointer&amp;lt;Int&amp;gt;.allocate(capacity: 10 * MemoryLayout&amp;lt;Int&amp;gt;.size)
// e para mudar o tamanho do array
b = realloc(b, 20*MemoryLayout&amp;lt;Int&amp;gt;.size).assumingMemoryBound(to: Int.self)
// e depois de usar
b.deallocate(capacity: 10 * MemoryLayout&amp;lt;Int&amp;gt;.size)

// Para pegar referencias de structs sem copiar valores nativos, em vez disso
let a_copy = test
// Faremos isso
let b_copy = UnsafeRawPointer(Unmanaged.passUnretained(test).toOpaque())
// E para acessar
Unmanaged&amp;lt;Int&amp;gt;.fromOpaque(b_copy).takeUnretainedValue()
&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;Lembre-se que &lt;code class=&quot;highlighter-rouge&quot;&gt;realloc&lt;/code&gt; é uma operação cara. A implementação de &lt;code class=&quot;highlighter-rouge&quot;&gt;Array&lt;/code&gt;, por exemplo, dobra o tamanho quando chegamos no limite. A regra de ouro é sempre que possível fazer um &lt;code class=&quot;highlighter-rouge&quot;&gt;loop&lt;/code&gt; e calcular o tamanho novo do array, em vez de realocar a cada novo &lt;em&gt;append&lt;/em&gt;.&lt;/p&gt;

    &lt;h4 id=&quot;52-tipos-genéricos&quot;&gt;5.2 Tipos genéricos&lt;/h4&gt;

    &lt;p&gt;Outro detalhe importante quando trabalhamos com dados é o tipo. Como o Random Forest não é um cara de grandes operações matemáticas, isso não vai importar muito pro nosso caso, e podemos usar &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt; sem dor no peito. De qualquer modo, é muito interessante que implementações de estruturas de dados para Aprendizado de Máquina sejam genéricas. &lt;a href=&quot;http://stackoverflow.com/questions/42696579/&quot;&gt;Apanhei um pouco&lt;/a&gt; pra deixar tudo genérico, mas considero que o resultado ficou bem interessante. Veja exemplos das declarações:&lt;/p&gt;

    &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;protocol&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Numeric&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Hashable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Comparable&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Matrix&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Numeric&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;TreeNode&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Numeric&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;protocol&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ClassifierAlgorithm&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;associatedtype&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NumericType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Numeric&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;RandomForest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Numeric&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;ClassifierAlgorithm&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NumericType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CrossValidation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Numeric&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;U&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;ClassifierAlgorithm&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;NSObject&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;where&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;U&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;NumericType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h4 id=&quot;53-operações-paralelas-com-operation&quot;&gt;5.3 Operações paralelas com &lt;code class=&quot;highlighter-rouge&quot;&gt;Operation&lt;/code&gt;&lt;/h4&gt;

    &lt;p&gt;No nosso algoritmo, nada impede que as árvores sejam construídas paralelamente. Em termos de performance, com testes rasos usando &lt;code class=&quot;highlighter-rouge&quot;&gt;Operation&lt;/code&gt;, o tempo de construir nove árvores de três em três é um terço de construir de uma em uma. Pois, vamos ao que interessa, começamos com um gerenciador de operários, também conhecido como sindicato 😂:&lt;/p&gt;

    &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;PendingOperations&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;queueName&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;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;concurrentOperations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;queueName&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;nv&quot;&gt;concurrentOperations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Int&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;queueName&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queueName&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;concurrentOperations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;concurrentOperations&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;lazy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;buildsInProgress&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;NSIndexPath&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Operation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]()&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;lazy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;buildQueue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;OperationQueue&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;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;queue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;OperationQueue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;queue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;queueName&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;queue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxConcurrentOperationCount&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;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;concurrentOperations&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queue&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;p&gt;Uma classe operária oprimida pelo sistema:&lt;/p&gt;

    &lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;TreeBuilder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Operation&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;main&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;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;p&gt;E para convocar uma greve:&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;for _ in 0..&amp;lt;self.treesCount {
	let treeBuilder = TreeBuilder.init()
	treeBuilder.completionBlock = {...}
	self.pendingOperations.buildQueue.addOperation(treeBuilder)
}
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;validação-cruzada-e-overfitting&quot;&gt;Validação Cruzada e &lt;em&gt;Overfitting&lt;/em&gt;&lt;/h3&gt;

    &lt;p&gt;Como validar o nosso modelo na prática? É comum ver em artigos da área frases como &lt;code class=&quot;highlighter-rouge&quot;&gt;to evaluate our accuracy we used 10-fold cross-validation [...] &lt;/code&gt;. Vamos explicar:&lt;/p&gt;

    &lt;p&gt;&lt;strong&gt;Acurácia&lt;/strong&gt; é uma métrica comum para algoritmos de ML, basicamente, previsões corretas/número de testes. Entenda:&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;language-Swift&quot;&gt;private func accuracy(actual:Array&amp;lt;T&amp;gt;, predicted:Array&amp;lt;T&amp;gt;) -&amp;gt; Double {
	let correct = zip(actual, predicted).reduce(0){ (a: Int, element) in
		var accumulator = a
		if element.0 == element.1 { accumulator += 1 }
		return accumulator
	}
	return Double(correct)/Double(actual.count)
}
&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;&lt;strong&gt;Overfitting&lt;/strong&gt; é o fenômeno que ocorre quando um modelo performa muito bem para para os dados de treino, e muito mal para os dados de teste. Veja um exemplo na seguinte imagem:&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;/img/farris/2017/overfitting.jpg&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;A linha verde é a função que gerou os dados. A linha azul é uma função criada por uma regressão. Dado um novo ponto da linha verde, será que o modelo azul vai predizer corretamente? &lt;em&gt;Não&lt;/em&gt;.&lt;/p&gt;

    &lt;p&gt;A criptonita do &lt;em&gt;overfitting&lt;/em&gt; é ter muitos dados. Quanto mais dados, melhor. &lt;em&gt;Sempre&lt;/em&gt;.&lt;/p&gt;

    &lt;p&gt;&lt;strong&gt;Validação Cruzada (K-fold Cross Validation)&lt;/strong&gt; é o conceito de dividir aleatoriamente o dataset em K subconjuntos de tamanho igual, e para cada subconjunto, usar ele de validação e os demais como teste. Entenda:&lt;/p&gt;

    &lt;div class=&quot;language-swift highlighter-rouge&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;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Array&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;foldCount&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;folds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Array&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Array&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;crossValidationSplit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;folds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;foldCount&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;fold&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;folds&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;trainData&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;datasetByRemovingFold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fold&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;testData&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fold&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;algorithm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;runClassifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainData&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;testData&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;p&gt;Validação cruzada ajuda também a reduzir um fantasma chamado &lt;em&gt;overfitting&lt;/em&gt;.&lt;/p&gt;

    &lt;p&gt;Vamos avaliar nosso algoritmo? Usando os parâmetros padrão, com 10 &lt;em&gt;folds&lt;/em&gt;, temos:&lt;/p&gt;

    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Fold 0 had accuracy 0.887876025524157
Fold 1 had accuracy 0.906107566089335
Fold 2 had accuracy 0.880583409298086
Fold 3 had accuracy 0.86873290793072
Fold 4 had accuracy 0.886052871467639
Fold 5 had accuracy 0.896991795806746
Fold 6 had accuracy 0.886052871467639
Fold 7 had accuracy 0.864175022789426
Fold 8 had accuracy 0.877848678213309
Fold 9 had accuracy 0.88514129443938
&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;p&gt;A acurácia média é &lt;code class=&quot;highlighter-rouge&quot;&gt;0,883&lt;/code&gt;. Ou seja, estamos predizento,em média, corretamente se 88% dos funcionários se demitiram ou não. Interessante né? Vamos olhar uma árvore construída:&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;/img/farris/2017/tree.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;Vamos olhar mais de perto nossa classificação:&lt;/p&gt;

    &lt;table&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th&gt; &lt;/th&gt;
          &lt;th&gt;Não se demitiu&lt;/th&gt;
          &lt;th&gt;Demitiu&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Achamos que não se demitiu&lt;/td&gt;
          &lt;td&gt;85%&lt;/td&gt;
          &lt;td&gt;12%&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Achamos que se demitiu&lt;/td&gt;
          &lt;td&gt;0%&lt;/td&gt;
          &lt;td&gt;3%&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;p&gt;&lt;em&gt;Opa&lt;/em&gt;. Parece que nosso classificador tem um viés. Isso está acontecendo porque o dataset é muito desbalanceado, ou seja, apenas 15% dos dados são de funcionários que pediram demissão. Vamos mudar nosso sampling para usar mais esta classe (&lt;em&gt;subsampling&lt;/em&gt;), ponderar as variáveis na hora de calcular o índice gini e na hora de predizer com o bagging, e mudar nossa métrica pra um indicador que lide melhor com os dados desbalanceados (&lt;a href=&quot;https://en.wikipedia.org/wiki/Cohen%27s_kappa&quot;&gt;kappa&lt;/a&gt;), como sugerido &lt;a href=&quot;http://statistics.berkeley.edu/sites/default/files/tech-reports/666.pdf&quot;&gt;no famoso artigo 666 de Berkeley&lt;/a&gt;:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;For each iteration in random forest, draw a bootstrap sample from the minority class. Randomly draw
the same number of cases, with replacement, from the majority class […] Since the RF classifier tends to be biased towards the majority class, we shall place a heavier penalty on misclassifying the minority class. We assign a weight to each class, with the minority class given larger weight&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3 id=&quot;conclusão&quot;&gt;Conclusão&lt;/h3&gt;

    &lt;p&gt;Nessa nossa breve jornada juntos, implementamos um classificador altamente prático, com um desempenho aceitável. Entendemos como lidar com dados, e a avaliar nossos modelos. Vimos como usar ponteiros, generics, e paralelizar operações em Swift 3. Descobrimos o possível perfil de quem pede demissão. Aprendemos como examinar o resultado do classificador.
Obrigado pela leitura. Até a próxima!
O código deste artigo pode ser encontrado &lt;a href=&quot;https://github.com/luksfarris/SwiftRandomForest&quot;&gt;neste repositório&lt;/a&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
  &lt;p&gt;Lucas Farris começou com programação em 2006, entrou no mercado mobile em 2011, em 2014 se formou em Ciência da Computação na Unicamp. Atualmente trabalha na Polônia, onde cuida de uma planta robo chamada &lt;em&gt;Саша&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;</content><author><name>Lucas Farris</name></author><category term="Tutorial" /><summary type="html">Geralmente, quando se fala em aprendizado de máquina para mobile, é mais comum ver códigos escritos em Python ou R, rodando do lado do servidor. No entanto, há casos em que compensa mais fazer o processamento localmente (por poder ser feito offline, e não sobrecarregar o server). Por isso o uso de Swift é justificável. Uns 4 anos atrás, eu falaria pra usar o OpenCV rodando nativo em C++, mas os tempos são outros. Se você, caro leitor, nunca teve contato com inteligência artificial, não tema; este artigo não assume que você conheça previamente nada sobre.</summary></entry><entry><title type="html">Desmistificando o Core Animation</title><link href="http://equinocios.com/animations/2017/03/20/desmistificando-o-core-animator/" rel="alternate" type="text/html" title="Desmistificando o Core Animation" /><published>2017-03-20T00:13:00+00:00</published><updated>2017-03-20T00:13:00+00:00</updated><id>http://equinocios.com/animations/2017/03/20/desmistificando-o-core-animator</id><content type="html" xml:base="http://equinocios.com/animations/2017/03/20/desmistificando-o-core-animator/">&lt;p&gt;Fala galera! Bem vindos a mais uma rodada do EquinociOS! Espero que estejam aproveitando e absorvendo tudo =D&lt;/p&gt;

&lt;p&gt;Bem, o artigo de hoje introduz um assunto que eu particularmente sempre corri dele e tentei ao máximo evitá-lo. Até que chegou o dia em que eu não tive como escapar e precisei encarar o “bixo”: &lt;code class=&quot;highlighter-rouge&quot;&gt;CORE Animation&lt;/code&gt;.
Vou falar que foi uma das batalhas mais satisfatórias que eu já enfrentei nesse mundo de desenvolvimento mobile, pois além de eu conseguir trabalhar minhas animações de uma forma muito melhor, abriu minha mente para detalhes que sempre passaram desapercebidos e que mudou muito a minha forma de encarar uma - até então - simples estrutura de tela/layout.&lt;/p&gt;

&lt;h3 id=&quot;lets-talk&quot;&gt;LETS TALK!&lt;/h3&gt;

&lt;p&gt;–&lt;/p&gt;

&lt;h1 id=&quot;core-animation&quot;&gt;Core Animation&lt;/h1&gt;

&lt;p&gt;Infraestrutura de renderização gráfica e animação, disponível para iOS e OS X, que você utiliza para animar as views e outros elementos visuais de sua aplicação.
(Sim, copiei do guide da Apple).
A propósito, vou pular esta parte introdutória (chata) que todo mundo está cansado de ver e pular pra parte “cool” da bagaça hehehe.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Sempre leiam o guide da Apple ;) (https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Certo, acredito que todos vocês em algum momento já se depararam com uns métodos de classe chamados:&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;animate&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;nf&quot;&gt;animateKeyframes&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;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;div class=&quot;language-objc highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;animateWith&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;animateKeyframesWith&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Estes, são métodos, ou melhor, &lt;code class=&quot;highlighter-rouge&quot;&gt;big helpers&lt;/code&gt; que encapsulam todo o processo de criação de um &lt;code class=&quot;highlighter-rouge&quot;&gt;CABasicAnimation&lt;/code&gt; ou de um &lt;code class=&quot;highlighter-rouge&quot;&gt;CAKeyframeAnimation&lt;/code&gt; por exemplo. Estes métodos são muito úteis, desde que usados com moderação e um certo bom senso, mas após nossa introdução você vai notar que pode ter um resultado mais apropriado utilizando o &lt;code class=&quot;highlighter-rouge&quot;&gt;Core Animation&lt;/code&gt;, dependendo da complexidade de suas animações.&lt;/p&gt;

&lt;p&gt;Antes de começar a ver como as animações acontecem na tela, precisamos entender um elemento bem importante: O &lt;code class=&quot;highlighter-rouge&quot;&gt;CALayer&lt;/code&gt;, que é de fato, onde as animações acontecem.&lt;/p&gt;

&lt;p&gt;Certo, vamos voltar mais um passo e entender um pouco do comportamento de uma &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt; em relação à animação.
Uma &lt;code class=&quot;highlighter-rouge&quot;&gt;instância do UIView&lt;/code&gt; modifica sua layer para delegar a renderização à estrutura de animação principal. Entretanto, as animações, quando adicionadas a uma layer, não modificam suas propriedades. A animação principal, mantém duas &lt;code class=&quot;highlighter-rouge&quot;&gt;hierarquias&lt;/code&gt; de layers: &lt;code class=&quot;highlighter-rouge&quot;&gt;model&lt;/code&gt; e &lt;code class=&quot;highlighter-rouge&quot;&gt;presentation layers&lt;/code&gt;.
Por exemplo, considerando uma animação de fade out, se em qualquer momento da animação você verificar o valor da opacidade da camada (&lt;code class=&quot;highlighter-rouge&quot;&gt;model layer&lt;/code&gt;), este valor será diferente do valor que está sendo apresentado na tela (&lt;code class=&quot;highlighter-rouge&quot;&gt;presentation layer&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Como falado anteriormente, não é possível definir as propriedades na presentation layer, mas você pode utilizar os valores para criar novas animações, ou interagir com outras camadas enquanto a animação acontece.&lt;/p&gt;

&lt;p&gt;É possível acessar qualquer uma dessas camadas utilizando os métodos &lt;code class=&quot;highlighter-rouge&quot;&gt;[CALayer presentationLayer]&lt;/code&gt; e &lt;code class=&quot;highlighter-rouge&quot;&gt;[CALayer modelLayer]&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Certo, vamos ver como tudo isso acontece na prática.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;cabasicanimation&quot;&gt;CABasicAnimation&lt;/h2&gt;

&lt;p&gt;Vamos pensar em uma animação bem básica. A primeira que vem à minha mente é deslocar um quadrado de um lado para outro. Logicamente, quando eu configurar meu &lt;code class=&quot;highlighter-rouge&quot;&gt;CABasicAnimation&lt;/code&gt;, vou passar para ele a propriedade que eu quero alterar, o valor inicial, o valor final e a duração:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/renatosarro/4753b9eb2dd7e22aa1383000514c4c1a.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;keyPath&lt;/code&gt;: KVC (Key value code) “position.x”, contém um membro CGPoint armazenada na propriedade position :)&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;fromValue&lt;/code&gt;: Posição Inicial&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;toValue&lt;/code&gt;: Posição Final&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;duration&lt;/code&gt;: Duração da animação&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Ao rodar a animação, observamos que ao terminar a animação, nosso quadrado pula da posição final para a posição inicial. Isto ocorre, pois como falado anteriormente, as animações não modificam as propriedades na presentation layer. Então, ao terminar a animação, a posição padrão continua sendo a inicial.
Podemos contornar isso, modificando a propriedade position, diretamente na layer:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class=&quot;language-objc highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;animation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;forKey&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;basicAnimation&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;position&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;CGPoint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;320&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Desta forma, ao terminar a animação, a posição do elemento (&lt;code class=&quot;highlighter-rouge&quot;&gt;presentation layer&lt;/code&gt;) será correspondente à posição final da animação (&lt;code class=&quot;highlighter-rouge&quot;&gt;model layer&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Uma outra abordagem é configurar duas propriedades do &lt;code class=&quot;highlighter-rouge&quot;&gt;CABasicAnimation&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Este objeto possui uma propriedade chamada &lt;code class=&quot;highlighter-rouge&quot;&gt;fillMode&lt;/code&gt; que determina o que vai acontecer ao final da animação. Vamos configurar esta propriedade com a string &lt;code class=&quot;highlighter-rouge&quot;&gt;kCAFillModeForwards&lt;/code&gt; que vai dizer para a animação permanecer em seu estado final.
Vamos também configurar a propriedade &lt;code class=&quot;highlighter-rouge&quot;&gt;isRemovedOnCompletion&lt;/code&gt; com o boolean false. Isto vai garantir que o objeto não seja removido automaticamente. Desta forma, nosso código ficará assim:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/renatosarro/396251ef6307475353b2ce3f718a58ee.js&quot;&gt;&lt;/script&gt;

&lt;blockquote&gt;
  &lt;p&gt;Utilize estas duas propriedades com muita parcimônia e as modifique apenas se houver uma real necessidade, pois quando trabalhamos com animações, é de estrema importância que as layers model e presentation estejam sincronizadas.
É importante ressaltar também, que o objeto da animação criada é copiado assim que adicionamos a alguma layer. Isto é bem interessante, pois podemos reutilizar o objeto em outras layers como por exemplo:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;script src=&quot;https://gist.github.com/renatosarro/c5d8881d055ad76b546e26ece695bec8.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Observe que, como a animação foi copiada para a layer da primeira view, ao configurarmos a propriedade beginTime para começar meio segundo depois, apenas a animação da layer da &lt;code class=&quot;highlighter-rouge&quot;&gt;view2&lt;/code&gt; é afetada, pois como falado, ao adicionar a animação à layer, é gerado uma cópia dela.&lt;/p&gt;

&lt;p&gt;PS: Podemos gastar mais um artigo inteiro falando só sobre como gerenciar o tempo de nossas animações. Acredite, estamos apenas começando e o &lt;code class=&quot;highlighter-rouge&quot;&gt;Core Animation&lt;/code&gt; possui uma infinidade de possibilidades para trabalhar as animações. Com certeza mais posts virão =D&lt;/p&gt;

&lt;p&gt;–&lt;/p&gt;

&lt;h3 id=&quot;agora-como-seria-esta-mesma-animação-sem-o-uso-do-core-animation&quot;&gt;Agora, como seria esta mesma animação sem o uso do Core Animation?&lt;/h3&gt;

&lt;script src=&quot;https://gist.github.com/renatosarro/dcc083ec91dfee76c46b5c48c56fd048.js&quot;&gt;&lt;/script&gt;

&lt;blockquote&gt;

  &lt;ul&gt;
    &lt;li&gt;Desta forma, a animação impacta diretamente na posição real do elemento (&lt;code class=&quot;highlighter-rouge&quot;&gt;presentation layer&lt;/code&gt;);&lt;/li&gt;
    &lt;li&gt;Vale ressaltar que se tratando de animações, o mais indicado é trabalhar sempre na model layer. Alterações na presentation layer precisam ser feitas com muito cuidado para evitar memory leak e uma animação não muito fluída.&lt;/li&gt;
    &lt;li&gt;Estaríamos limitados a animações simples, como um fade out. Mas vamos pensar em um cenário onde nosso elemento passe por vários estados até chegar em sua posição final. Utilizar essa abstração oferecida pela &lt;code class=&quot;highlighter-rouge&quot;&gt;UIView&lt;/code&gt; já não seria muito indicado.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;Já que falamos sobre vários estados, vou aproveitar o gancho para puxar um outro elemento bem bacana presente no Core &lt;code class=&quot;highlighter-rouge&quot;&gt;Animation&lt;/code&gt;:&lt;/p&gt;

&lt;h1 id=&quot;cakeyframeanimation&quot;&gt;CAKeyframeAnimation&lt;/h1&gt;

&lt;p&gt;Não sei quantos vieram desta época, mas minha primeira experiência como desenvolvedor foi com Action Script. Era o boom do Flash. Fantástico, brilhante, inovador, perfeito para ter experiências mais interativas e claro, animadas.&lt;/p&gt;

&lt;p&gt;Bem, o conceito básico para qualquer animação é pensar nela em forma de &lt;code class=&quot;highlighter-rouge&quot;&gt;Key frames&lt;/code&gt;. Já ouviram falar de Folioscópio, ou Flipbook?&lt;/p&gt;

&lt;p&gt;É exatamente assim que uma animação funciona. Cada quadro (frame) possui o elemento em um estado diferente, onde colocando todos os quadros para passar de forma contínua, forma um desenho animado.&lt;/p&gt;

&lt;p&gt;Sim, posso &lt;code class=&quot;highlighter-rouge&quot;&gt;e devo&lt;/code&gt; utilizar o mesmo conceito ao elaborar minha animação.&lt;/p&gt;

&lt;p&gt;Imagine que nossa view em vez de apenas se deslocar para a direta, ela vá até o centro, volte para o início e depois vá para o fim da tela.&lt;/p&gt;

&lt;p&gt;O primeiro passo, é fazer um array de valores.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;values&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;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;160&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;320&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Depois disso, vamos criar um array de &lt;code class=&quot;highlighter-rouge&quot;&gt;timming&lt;/code&gt;, que vai ser relativo aos itens de estado. Ou seja, para cada posição, teremos um tempo que irá dizer quanto vai levar para a nossa view estar naquela posição.&lt;/p&gt;

&lt;div class=&quot;language-swift highlighter-rouge&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;times&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;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&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;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Perceba que esta lista diz que minha view começa na posição 20. Após 0,5 segundo, ela estará na posição 160. Após 1 segundo, na posição 20 e após 2 segundos, na posição 320. Ou seja, minha animação terá a duração de 2 segundos.&lt;/p&gt;

&lt;p&gt;Vamos então criar nosso objeto &lt;code class=&quot;highlighter-rouge&quot;&gt;CAKeyframeAnimation&lt;/code&gt;.&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/renatosarro/7dd14ca9892d894653f8f185d18f6409.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Podemos notar uma propriedade nova. A &lt;code class=&quot;highlighter-rouge&quot;&gt;isAdditive&lt;/code&gt;. Configurando esta propriedade como verdadeiro, significa que o valor especificado pela animação, será adicionado à árvore de renderização atual. Isso nos permite reutilizar a mesma animação para qualquer elemento que precise ter o mesmo comportamento.&lt;/p&gt;

&lt;p&gt;–&lt;/p&gt;

&lt;p&gt;Olhando assim, o Core Animation não parece tão monstruoso hehe… Na verdade ele pode e vai auxiliar muito quando precisar trabalhar mais com o lado animado da coisa =D&lt;/p&gt;

&lt;p&gt;Claro, esta, é apenas uma introdução. Com isso podemos ir brincando com keyPahts, keyFrames e ver o que podemos fazer de mais complexo exercitando muito estas propriedades básicas, mas tão importantes se tratando de animação.&lt;/p&gt;

&lt;p&gt;Há uma infinidade de possibilidades quando falamos de animações e com certeza falaremos mais sobre isso.&lt;/p&gt;

&lt;h1 id=&quot;carry-on&quot;&gt;Carry on!&lt;/h1&gt;</content><author><name>Renato Sarro Matos</name></author><category term="animations" /><summary type="html">Fala galera! Bem vindos a mais uma rodada do EquinociOS! Espero que estejam aproveitando e absorvendo tudo =D</summary></entry><entry><title type="html">Server-side: características de um servidor</title><link href="http://equinocios.com/server/2017/03/19/server-side-caracteristicas-de-um-servidor/" rel="alternate" type="text/html" title="Server-side: características de um servidor" /><published>2017-03-19T00:00:00+00:00</published><updated>2017-03-19T00:00:00+00:00</updated><id>http://equinocios.com/server/2017/03/19/server-side-caracteristicas-de-um-servidor</id><content type="html" xml:base="http://equinocios.com/server/2017/03/19/server-side-caracteristicas-de-um-servidor/">&lt;h1 id=&quot;antes-de-começar&quot;&gt;Antes de começar&lt;/h1&gt;

&lt;p&gt;Este artigo trata, basicamente, de características do sistema operacional. Pode
parecer um pouco fora dos assuntos do EquinociOS, mas é algo bastante
relevante. Desde que a Apple liberou a linguagem Swift como um projeto de
código-aberto, muita gente vem usando a linguagem para desenvolver software do
lado do servidor. Assim, torna-se bastante relevante o conhecimento que é
apresentado neste artigo pois o software servidor executa em um ambiente que
fará algumas exigências para o seu correto funcionamento.&lt;/p&gt;

&lt;p&gt;É importante ter em mente que o ambiente no qual seu software executa precisa
ser respeitado. Este ambiente proporcionará vantagens, e também desvantagens,
que precisam ser entendidas e avaliadas. O intuito é integrar bem o seu software
com este ambiente e tirar proveito das vantagens evitando-se as desvantagens.&lt;/p&gt;

&lt;p&gt;Considerando-se que o software do lado do servidor normalmente funciona em
esquema 24 x 7 x 365, a boa integração com o ambiente aumenta bastante a
confiabilidade e a robustez. Portanto, é importante conhecer, mesmo que
superficialmente, o ambiente de execução do seu servidor.&lt;/p&gt;

&lt;h1 id=&quot;o-que-é-o-servidor&quot;&gt;O que é o servidor?&lt;/h1&gt;

&lt;p&gt;O conceito de servidor não é novo. Apareceu na série 360 da IBM em 1964. Desde
então vem sofrendo transformações até chegar no modelo em nuvem conforme temos
hoje. Mas, o que raios é o servidor?&lt;/p&gt;

&lt;p&gt;Olhando pela ótica do software, que é a premissa deste artigo, o servidor é um
artefato de software cuja função é prover serviços à outros artefatos de
software, chamados de &lt;em&gt;clientes&lt;/em&gt;. Esta não é uma definição formal nem muito
menos precisa. A intenção é partirmos desta definição para entender como
projetar um servidor de software de maneira a usar as principais características
do sistema operacional no qual estará hospedado.&lt;/p&gt;

&lt;p&gt;Hoje em dia o papel principal do servidor é prover serviços a clientes leves, ou
&lt;em&gt;thin clients&lt;/em&gt;, normalmente aplicativos para celulares. Todo o processamento
pesado e o armazenamento fica por conta do servidor, deixando o cliente com a
tarefa de organizar, logicamente, os fluxos de trabalho disponíveis para que o
usuáio seja atendido em determinada funcionalidade.&lt;/p&gt;

&lt;p&gt;O servidor pode ser uma ou mais peças de software trabalhando em conjunto,
formando um sistema que pode ser agregado ou distribuído. Para o cliente, o
servidor é um só, mesmo que sejam várias máquinas físicas diferentes, vários
sistemas de software criados por várias linguagens diferentes, interagindo entre
si através das mais diversas formas de integração.&lt;/p&gt;

&lt;h1 id=&quot;linux-e-unix&quot;&gt;Linux e Unix&lt;/h1&gt;

&lt;p&gt;Nos dias de hoje o sistema operacional mais popular para &lt;em&gt;back-end&lt;/em&gt; é, sem
dúvida, o Linux. O Unix é um sistema muito popular no ambiente corporativo,
apesar das vendas deste sistema decrescer ano após ano. Sendo rigoroso, o Unix
não é Linux e Linux não é Unix. São sistemas completamente diferentes, apesar
das suas similaridades.&lt;/p&gt;

&lt;p&gt;Apesar do foco deste artigo ser o Linux, os princípios e conceitos aqui
apresentados valem para o Unix. Vale lembrar que o FreeBSD é um Unix e não
Linux. A camada de compatibilidade entre o BSD e o Linux é tão boa e
transparente que ela faz com que praticamente tudo o que executa em um sistema
seja executado em outro.&lt;/p&gt;

&lt;p&gt;De toda forma vou intercambiar os termos Unix e Linux ao longo do texto,
tratando tudo como se fosse Unix por questão de simplicidade. Se houver algo que
seja inerente a um sistema, deixarei explícito para que não haja confusões.&lt;/p&gt;

&lt;p&gt;Vamos começar por alguns conceitos básicos que serão usados através do restante
do texto. Com o intuito de equalizar o conhecimento, apresento de forma bastante
rápida estes conceitos.&lt;/p&gt;

&lt;h2 id=&quot;daemon&quot;&gt;Daemon&lt;/h2&gt;

&lt;p&gt;Apesar do termo lembrar os demônios cristãos, ou seja, entidades malévolas, o
termo &lt;em&gt;daemon&lt;/em&gt; foi emprestado do termo grego &lt;em&gt;daimon&lt;/em&gt; que refere-se a entidades
naturais benignas e que estão sempre presentes em nossas vidas.&lt;/p&gt;

&lt;p&gt;A despeito da questão religiosa, um &lt;em&gt;daemon&lt;/em&gt; é, na verdade, um processo autônomo
que é executado em segundo plano, fornecendo ou executando algum tipo de
serviço. Normalmente os daemons no Unix/Linux são processos iniciados durante a
carga do sistema, através de um sistema de inicialização como o System V ou o
upstart do Ubuntu.&lt;/p&gt;

&lt;p&gt;Uma vez iniciados, estes processos normalmente terminam quando o sistema é
reiniciado, ou seja, são processos de execução longa, projetados para
permanecerem funcionando por longos períodos de tempo.&lt;/p&gt;

&lt;h2 id=&quot;ipc&quot;&gt;IPC&lt;/h2&gt;

&lt;p&gt;IPC é uma sigla que significa &lt;em&gt;Inter-Process Communication&lt;/em&gt;. Tanto o Unix quanto
o Linux implementam várias formas de comunicação inter-processo:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;pipes&lt;/em&gt; para escrita e leitura síncrona de dados;&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;message queues&lt;/em&gt; para escrita e leitura assíncrona de dados;&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;semáforos&lt;/em&gt; para o controle atômico de recursos compartilhados;&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;shared memory&lt;/em&gt; para compartilhamento de arenas de memória;&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;sockets&lt;/em&gt;, em particular os sockets Unix, para troca assíncrona de dados
arbitrários;&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;sinalização&lt;/em&gt;, usado para entregar eventos a processos arbitrários.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Muitos autores não consideram a sinalização como parte do IPC. No entanto, é uma
característica importante do sistema operacional pois é através dos sinais que o
sistema de inicialização comunica-se com os deamons.&lt;/p&gt;

&lt;p&gt;Os sinais são eventos assíncronos que podem, ou não, ser capturados e tratados
por um processo. Apesar dos sinais serem números inteiros, eles são limitados
pelo sistema operacional. Os sinais são definidos no arquivo de cabeçalho
&lt;em&gt;signal.h&lt;/em&gt;, que normalmente está no diretório &lt;code class=&quot;highlighter-rouge&quot;&gt;/usr/include&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;system-calls&quot;&gt;System Calls&lt;/h2&gt;

&lt;p&gt;Sempre que seu programa precisa interagir com o sistema operacional ele fará uma
chamada de sistema, ou &lt;em&gt;system call&lt;/em&gt;. Mesmo que você não o faça diretamente,
algumas operações sempre terminam em uma chamada de sistema, como alocação de
memória, abertura e escrita em arquivos, comunicação por rede e por aí vai.&lt;/p&gt;

&lt;p&gt;As chamadas de sistema são muito importantes pois permitem que o seu software
interaja com o kernel do sistema operacional, trazendo uma série de vantagens
importantes no que tange a integração de sistemas.&lt;/p&gt;

&lt;h2 id=&quot;linguagem-c&quot;&gt;Linguagem C&lt;/h2&gt;

&lt;p&gt;Por que coloco a linguagem C na lista de definições? A resposta é muito simples:
tanto o Unix quanto o Linux são sistemas operacionais escritos em C. Os &lt;em&gt;system
calls&lt;/em&gt; são todos escritos em C e são acessados através de bibliotecas escritas
em C do próprio sistema operacional. Assim, é impossível falar em Linux e Unix
sem mencionar esta linguagem.&lt;/p&gt;

&lt;p&gt;Para quem programa em Swift e deseja criar software do lado do servidor aqui vai
a primeira dica: se você não sabe C, procure aprender. Infelizmente Swift não
possui, nativamente, uma forma de realizar chamadas de sistema. A captura de
sinais, criação de processos-filhos e outras características do sistema
operacional só são conseguidas se você interfacear seu código Swift com wrappers
escritos em C.&lt;/p&gt;

&lt;p&gt;Na plataforma Apple a integração é quase &lt;em&gt;out-of-the-box&lt;/em&gt; ao importar-se o
módulo &lt;em&gt;Darwin&lt;/em&gt;. Porém, muita coisa importante fica de fora. Além disso, as
bibliotecas da Apple acabam se tornando um estorvo. Por exemplo, a função
&lt;em&gt;sigaction&lt;/em&gt; usa uma estrutura como um dos parâmetros para instalação de handlers
de sinal. No caso da Apple, esta estrutura contém uma união que é mascarada por
macros. Para a linguagem C isso é irrelevante, mas para o Swift, faz toda a
diferença. O código Swift neste caso, compilará para a plataforma Apple se a
estrutura for usada conforme definida, e falhará para o Linux. A recíproca é
totalmente verdadeira, ou seja, o código feito para Linux não compilará na
plataforma Apple. É necessário, portanto, fazer um wrapper em C para permitir o
funcionamento &lt;em&gt;cross platform&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;processo&quot;&gt;Processo&lt;/h2&gt;

&lt;p&gt;Sempre que um executável entra em execução no Unix e no Linux, ele cria um
&lt;em&gt;processo&lt;/em&gt;. O processo é uma instância de execução do seu executável. Em linhas
gerais, o mesmo executável pode ter diversas instâncias de execução, podendo ser
chamado quantas vezes o usuário bem desejar. A cada instância de execução é
asssociado um número inteiro que identifica este processo para o sistema
operacional. Este número é chamado de &lt;em&gt;PID&lt;/em&gt;, de &lt;em&gt;process identification&lt;/em&gt;. A
estrutura de numeração de processos nos sistemas operacionais Unix e Linux é uma
lista circular. Isto é feito para que os números de processo sejam
reaproveitados. Assim, o processo criado para um determinado executável pode ter
atribuído um número inteiro qualquer, repetindo-se ou não.&lt;/p&gt;

&lt;p&gt;Normalmente o processo cujo PID é 1 é o processo de inicialização do sistema, o
processo que é pai de todo mundo, chamado de &lt;em&gt;init&lt;/em&gt;. Tudo no Unix e Linux é
iniciado pelo &lt;em&gt;init&lt;/em&gt;. Os usuários, quando autenticados e conectados a estes
sistemas utilizam processos que foram inicialmente criados pelo init, mas que
deram origem a outros processos.&lt;/p&gt;

&lt;h3 id=&quot;processo-filho&quot;&gt;Processo-filho&lt;/h3&gt;

&lt;p&gt;O processo-filho é um processo que é criado por outro processo. O processo-filho
tem como característica um número inteiro chamado de &lt;em&gt;PPID&lt;/em&gt;, ou &lt;em&gt;parent process
ID&lt;/em&gt;. O processo-pai pode ser um processo-filho de outro processo e este fato
implica na criação de uma árvore de processos.&lt;/p&gt;

&lt;p&gt;As implicações disso são importantes para o correto design de um software do
lado do servidor, conforme veremos a seguir.&lt;/p&gt;

&lt;h1 id=&quot;daemons-e-o-init&quot;&gt;Daemons e o init&lt;/h1&gt;

&lt;p&gt;Um daemon é um programa comum, como qualquer outro, porém com ciclo longo de
execução. Normalmente, o daemon executa apenas uma única instância na máquina
onde está hospedado. Via de regra, os daemons são iniciados pelo sistema de
inicialização do Unix, podendo ser um sistema baseado no System V ou em outra
forma de inicialização. Normalmente os sistemas Linux têm maneiras um pouco
diferentes de inicialização, como o ubuntu que está movendo-se para o &lt;em&gt;upstart&lt;/em&gt;,
um sistema de inicialização um pouco mais eficiente e mais flexível que o antigo
System V.&lt;/p&gt;

&lt;p&gt;O sistema de inicialização não é, na verdade, importante para os propósitos
deste texto. O fato é que todo daemon pode ser iniciado pelo init e a
inicialização garante que o processo iniciado não estará associado a nenhum
terminal. E aqui começamos a ver o que é realmente importante ter no seu
processo do lado do servidor para que ele intereja de forma adequada com o
sistema operacional.&lt;/p&gt;

&lt;h2 id=&quot;sinalização&quot;&gt;Sinalização&lt;/h2&gt;

&lt;p&gt;Uma das formas que o sistema de inicialização tem de comunicar-se com o seu
software é através do envio de sinais. Os sinais são números inteiros e cada
número tem seu significado. A listagem de sinais normalmente é compilada através
de um conjunto de macros declarados em &lt;em&gt;signal.h&lt;/em&gt;. Este arquivo normalmente
reside no diretório &lt;code class=&quot;highlighter-rouge&quot;&gt;/usr/include&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A sinalização ocorre de maneira assíncrona e interrompe qualquer que seja o
fluxo em execução no seu programa, retomando ao ponto de interrupção tão logo o
sinal seja tratado ou ignorado. É importante ter em mente, no entanto, que nem
todo sinal pode ser tratado. Alguns sinais, em especial &lt;code class=&quot;highlighter-rouge&quot;&gt;SIGKILL&lt;/code&gt;, não podem ser
capturados nem tratados pelo seu software. O seu comportamento acaba sendo
definido pelo sistema operacional. Por exemplo, &lt;code class=&quot;highlighter-rouge&quot;&gt;SIGKILL&lt;/code&gt; elimina o processo que
executa o seu software da memória, não importa o que o seu software esteja
fazendo. Este é um dos sinais que não podem ser nem capturados nem tratados.&lt;/p&gt;

&lt;h3 id=&quot;sinais-notáveis&quot;&gt;Sinais notáveis&lt;/h3&gt;

&lt;p&gt;Alguns sinais são importantes pois são usados com frequência pelos sistemas de
inicialização e controle de processos. Em particular os sinais &lt;code class=&quot;highlighter-rouge&quot;&gt;SIGTERM&lt;/code&gt; e
&lt;code class=&quot;highlighter-rouge&quot;&gt;SIGHUP&lt;/code&gt; são usados para terminar ou reiniciar um daemon, respectivamente. Assim
é importante capturar e tratar &lt;code class=&quot;highlighter-rouge&quot;&gt;SIGTERM&lt;/code&gt;para que seu daemon seja finalizado de
forma graciosa; e &lt;code class=&quot;highlighter-rouge&quot;&gt;SIGHUP&lt;/code&gt; para que seu processo possa reiniciar-se, ou seja,
recarregar a configuração e iniciar do zero, como se estivesse sendo carregado
pela primeira vez.&lt;/p&gt;

&lt;p&gt;Ao capturar e tratar os sinais &lt;em&gt;notáveis&lt;/em&gt; você estará melhorando a integração do
seu software com sistemas Unix, tornando-o mais adequado para uso com os
sistemas de inicialização, seja System V ou seja via upstart.&lt;/p&gt;

&lt;h2 id=&quot;daemonização&quot;&gt;Daemonização&lt;/h2&gt;

&lt;p&gt;Se você abrir um terminal, seja um Xterm, ou um terminal de texto pendurado a
uma linha serial, qualquer processo que você iniciar manualmente estará
associado ao seu terminal. Este é um trabalho que o kernel faz no intuito de
finalizar qualquer processo caso seu terminal seja desconectado. Esta
característica é boa e não é.&lt;/p&gt;

&lt;p&gt;O fato é que pode ser necessário reiniciar um daemon manualmente. Digamos que
seja necessário realizar uma manutenção no servidor, por algum motivo. Portanto,
é imperativo que seu daemon não esteja associado com o seu terminal pois, se
estiver, ao fechar o seu terminal o processo cai.&lt;/p&gt;

&lt;p&gt;Os sistemas de inicialização já garantem que o seu daemon seja executado
dissociado de um terminal. Porém, a daemonização pode auxiliá-no no design do
seu daemon simplificando uma série de coisas, como a reinicialização &lt;em&gt;a quente&lt;/em&gt;
do seu processo, conforme expliquei na seção sobre sinais notáveis.&lt;/p&gt;

&lt;p&gt;Normalmente você vai iniciar o seu daemon através do sistema de inicialização,
via &lt;em&gt;start&lt;/em&gt;, &lt;em&gt;initctl&lt;/em&gt; ou algum comando especial que reside no &lt;em&gt;/sbin&lt;/em&gt; ou
&lt;em&gt;/usr/sbin&lt;/em&gt; dependendo do seu Unix ou Linux.&lt;/p&gt;

&lt;p&gt;A daemonização consiste em dissociar seu processo do seu terminal ativo. Isto é
algo muito simples de ser feito, na realidade. A ideia por trás disso é criar um
processo-filho e o processo-filho criar outro processo-filho que, em última
instância, executará o código do seu daemon, tomando-se o cuidado de terminar os
processos-pai sem aguardar o retorno dos processos-filhos.&lt;/p&gt;

&lt;p&gt;Neste cenário o processo neto é adotado pelo sistema de inicialização e
torna-se, efetivamente, dissociado do seu terminal. Isto é tão simples de ser
realizado que dá para fazer num shell script:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;a=0;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;while&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;$a&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;-lt&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;];&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;do&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;sleep&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;10;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;a=$((a+1));&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;echo&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&quot;Executado $a vezes&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;$HOME/output.txt;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;}&amp;amp;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;}&amp;amp;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Este comando meio esquisito inicia um contador que escreve um arquivo texto a
cada 10 segundos, durante 100 segundos. Se antes de finalizar o script você
fechar o seu terminal o arquivo &lt;em&gt;output.txt&lt;/em&gt; continuará a crescer.&lt;/p&gt;

&lt;p&gt;O truque é bem simples: cria-se um processo-filho e dentro deste processo-filho
cria-se outro processo-filho. Em C, teríamos algo assim usando a forma clássica
de criação de processos-filho:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;if (fork() == 0) {
    if (fork() == 0) {
        /* Aqui vai o seu processo. Este é o processo-neto */
    } else {
        /* Termina o processo-fiho sem esperar o sincronismo */
        exit(0);
    }
} else {
    /* Termina o processo-pai sem esperar para sincronizar. */
    exit(0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Trabalhar com multi-processos no Unix sempre foi um assunto confuso. A chamada
de sistema &lt;em&gt;fork&lt;/em&gt; retorna ao processo-pai o PID do processo-filho. Para o
processo-filho, o retorno do system call é zero. O que não fica explícito no
código é que ao chamar o &lt;em&gt;fork&lt;/em&gt;, o seu processo se divide em dois. O que está no
&lt;code class=&quot;highlighter-rouge&quot;&gt;else&lt;/code&gt; do &lt;code class=&quot;highlighter-rouge&quot;&gt;if (fork() == 0)&lt;/code&gt; é o processo-pai. O que está no &lt;code class=&quot;highlighter-rouge&quot;&gt;then&lt;/code&gt; é o
processo-filho.&lt;/p&gt;

&lt;p&gt;As chamadas ao system call &lt;code class=&quot;highlighter-rouge&quot;&gt;exit&lt;/code&gt; faz com que o processo seja finalizado
imediatamente. No caso do exemplo, os processos-pai serão finalizados sem
aguardar os processos-filho retornarem. Como dito, em uma situação como esta, o
processo-filho não tem com quem sincronizar para retornar pois os processos-pai
já foram reciclados pelo sistema. Assim, o processo &lt;em&gt;init&lt;/em&gt; assume o processo
órfão e este fica dissociado de um terminal, passando a rodar em segundo plano.&lt;/p&gt;

&lt;p&gt;De uma forma mais moderna, pode-se usar a função &lt;code class=&quot;highlighter-rouge&quot;&gt;posix_spawn&lt;/code&gt; para carregar
novamente o seu processo em outro espaço de endereçamento. A diferença entre
usar isto e a chamada &lt;code class=&quot;highlighter-rouge&quot;&gt;fork&lt;/code&gt; é que esta última pode gerar problemas com os
frameworks da Apple, em particular se você estiver programando em Swift.&lt;/p&gt;

&lt;p&gt;A chamada a &lt;code class=&quot;highlighter-rouge&quot;&gt;posix_spawn&lt;/code&gt; gera um pouco mais de trabalho. Esta função cria um
processo-filho de forma diferente, iniciando o novo processo literalmente do
zero. Você precisa informar a &lt;code class=&quot;highlighter-rouge&quot;&gt;posix_spawn&lt;/code&gt; qual o caminho completo do
executável, ou seja, esta função cria um processo arbitrário totalmente novo que
pode, ou não, ser igual ao processo em execução.&lt;/p&gt;

&lt;p&gt;O trabalho extra é que será necessário processar a linha de comando para que seu
programa saiba que está executando como um &lt;em&gt;child process&lt;/em&gt;. Este é o método
preferido se você escrever seu código em Swift. O compilador LLVM sequer gera
executável se você tentar usar o &lt;code class=&quot;highlighter-rouge&quot;&gt;fork&lt;/code&gt; justamente porque este system call é
danoso para os frameworks da Apple.&lt;/p&gt;

&lt;p&gt;Como o system call &lt;code class=&quot;highlighter-rouge&quot;&gt;fork&lt;/code&gt; é mais simples, achei melhor usá-lo para explicar o
princípio, que continua rigorosamente o mesmo se você usar &lt;code class=&quot;highlighter-rouge&quot;&gt;posix_spawn&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;syslog-e-o-logging-do-seu-daemon&quot;&gt;Syslog e o logging do seu daemon&lt;/h2&gt;

&lt;p&gt;Existem diversas bibliotecas de logging por aí afora, que trabalham com níveis
de logging e mais uma penca de coisas. Tanto o Linux quanto o Unix oferecem um
sistema completo de logging que normalmente é ignorado pelos desenvolvedores:
&lt;em&gt;syslog&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;O &lt;em&gt;syslog&lt;/em&gt; tem diversas vantagens que sobrepujam qualquer outro sistema de
logging:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;se o seu processo morre inesperadamente, o log é preservado. Se alguma
informação ficou pendente, ela é salva no log pois a comunicação com o
&lt;em&gt;syslog&lt;/em&gt; não é bufferizada.&lt;/li&gt;
  &lt;li&gt;o logging é feito por um daemon, &lt;em&gt;syslogd&lt;/em&gt; normalmente. A comunicação é feita
via pipes ou Unix sockets e é extremamente rápida.&lt;/li&gt;
  &lt;li&gt;o &lt;em&gt;syslog&lt;/em&gt; faz rotação de log, compactando arquivos antigos e eliminando
arquivos muito antigos.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Normalmente o &lt;em&gt;syslog&lt;/em&gt; salva as informações de logging no diretório
&lt;code class=&quot;highlighter-rouge&quot;&gt;/var/log&lt;/code&gt;. Este diretório pode variar de acordo com a sua distribuição de Linux
ou sabor de Unix. Algumas distros salvam os logs em &lt;code class=&quot;highlighter-rouge&quot;&gt;/var/spool/log&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Fazer saídas para &lt;em&gt;stdout&lt;/em&gt; ou &lt;em&gt;stderr&lt;/em&gt; normalmente não é uma boa ideia. Alguns
sistemas de inicialização fazem o redirecionamento destes streams para arquivos
de log, mas isto não é garantido. Se você gosta de prints da vida, uma dica é:
não faça isso. Use o &lt;em&gt;syslog&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;scheduling&quot;&gt;Scheduling&lt;/h2&gt;

&lt;p&gt;Este é um assunto muito mais voltado à administração do sistema do que
efetivamente ao seu processo. Mas vale a pena passar o olho nisto pois é
possível para um processo alterar a sua própria prioridade.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Scheduling&lt;/em&gt; tem a ver com a forma como o seu processo será executado dentro do
Linux/Unix. O sistema operacional divide um &lt;em&gt;quantum&lt;/em&gt; arbitrário de tempo com
base na prioridade de cada processo, dando a cada processo a oportunidade de
executar. Quanto maior a prioridade de um processo, mais tempo ele terá dentro
da CPU.&lt;/p&gt;

&lt;p&gt;Como o Unix é um sistema operacional multi-processo, o &lt;em&gt;scheduling&lt;/em&gt; foi a forma
encontrada para compartilhar a CPU com os diversos processos que executam ao
mesmo tempo pois a CPU é uma só. Se há 4 cores, até 4 processos executam
realmente em paralelo. Os demais precisam aguardar para executar.&lt;/p&gt;

&lt;p&gt;O &lt;em&gt;scheduling&lt;/em&gt; implica na performance da sua aplicação. Quanto maior for a
prioridade, mais rápido é a execução de um processo. A prioridade permite que
seu processo possa, automaticamente, escalar-se para usar mais e mais CPU à
medida em que a demanda aumenta. Assim, o seu processo começa a usar mais CPU e
torna-se mais eficiente.&lt;/p&gt;

&lt;h2 id=&quot;multi-processos&quot;&gt;Multi-processos&lt;/h2&gt;

&lt;p&gt;Não é incomum um daemon ser arquitetado para usar diversos processos, cada um
com uma finalidade bem determinada. Um &lt;em&gt;pattern&lt;/em&gt; muito comum é o &lt;em&gt;pipeline&lt;/em&gt;. A
ideia do pipeline é implementar um workflow usando vários processos. Cada passo
do workflow é realizado por um processo que, ao finalizar, passa para o processo
subsequente a requisição com o resultado do seu processamento.&lt;/p&gt;

&lt;p&gt;Este tipo de design é muito usado para permitir o processamento paralelo e exige
alguma forma de comunicação entre os processos. Ao invés de inventar moda, use
alguma forma de IPC: pipes, message queues, semáforos, etc. Tudo isto está
presente e disponível no seu Linux ou Unix há anos, sendo uma maneira muito
eficiente e estável de permitir que vários processos troquem informações entre
si.&lt;/p&gt;

&lt;p&gt;Assim, quando vários processos estão na mesma máquina, não há a necessidade de
usar sistemas de mensagens distribuídas, como o MQ Series ou o Rabbit MQ. O
próprio Linux/Unix já lhe dá as message queues prontas para uso.&lt;/p&gt;

&lt;h1 id=&quot;swift-server-side&quot;&gt;Swift Server-side&lt;/h1&gt;

&lt;p&gt;A linguagem Swift tem ganhado destaque no desenvolvimento de aplicações do lado
do servidor. Porém, Swift não tem wrappers nativos para integrar chamadas de
sistema com a linguagem. Assim, a forma de realizar isto é importar código C
para o seu software, o que muitas vezes exige a necessidade de escrever wrappers
em C antes de importá-los para o seu código em Swift.&lt;/p&gt;

&lt;p&gt;Por exemplo, a função &lt;code class=&quot;highlighter-rouge&quot;&gt;sigaction&lt;/code&gt; tem uma implementação no macOS que exige
que um wrapper C seja criado no intuito de manter o código portável para o
Linux. Assim, cedo ou tarde será necessário escrever algum código em C para que
você integre, adequadamente, o seu servidor Swift no Linux ou Unix.&lt;/p&gt;

&lt;h1 id=&quot;conclusão&quot;&gt;Conclusão&lt;/h1&gt;

&lt;p&gt;A correta integração do software server-side com o sistema operacional traz
benefícios inúmeros, tornando seu software mais robusto e usando as
características do sistema operacional como o &lt;em&gt;syslog&lt;/em&gt;. A integração com o
sistema de inicialização também é importante para garantir a correta
inicialização/término da sua aplicação.&lt;/p&gt;

&lt;p&gt;Como os sistemas Unix foram escritos basicamente em C, cedo ou tarde será
necessário escrever algum código para que seja possível integrar-se o seu
servidor Swift ao sistema operacional.&lt;/p&gt;</content><author><name>Ronaldo Faria Lima</name></author><category term="server" /><summary type="html">Antes de começar</summary></entry></feed>