<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexey Antonov on Medium]]></title>
        <description><![CDATA[Stories by Alexey Antonov on Medium]]></description>
        <link>https://medium.com/@iamalexantonov?source=rss-ee36fdf90367------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*M9ykKk9dMLs8y2USZCjp_g.jpeg</url>
            <title>Stories by Alexey Antonov on Medium</title>
            <link>https://medium.com/@iamalexantonov?source=rss-ee36fdf90367------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:31:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamalexantonov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Переворачиваем календарь на SwiftUI]]></title>
            <link>https://iamalexantonov.medium.com/%D0%BF%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%D1%80%D0%B0%D1%87%D0%B8%D0%B2%D0%B0%D0%B5%D0%BC-%D0%BA%D0%B0%D0%BB%D0%B5%D0%BD%D0%B4%D0%B0%D1%80%D1%8C-%D0%BD%D0%B0-swiftui-f6faea96c0ea?source=rss-ee36fdf90367------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6faea96c0ea</guid>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alexey Antonov]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 12:36:33 GMT</pubDate>
            <atom:updated>2021-09-03T12:36:33.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIPNm0bnGN9kmKk49ZnDZQ.jpeg" /><figcaption>By Maria Yalanska from Unsplash</figcaption></figure><p>Так как у себя в блоге я рассказываю о SwiftUI, то предлагаю сегодня в честь известного дня сделать свой календарь — с кострами рябин и третьим сентября.</p><p>Приступим сразу к делу: открываем <strong>Xcode</strong> (если вдруг у вас его ещё нет, то срочно бегите в AppStore — он там халявный) и создаём новый проект. Выбираем <strong>iOS</strong> и тип приложения <strong>App</strong>. Продолжаем при помощи кнопки <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_w-RG41RMmjlaYMau5Mqdg.png" /></figure><p>В появившемся окне вводим имя проекта и выбираем <strong>SwiftUI</strong> в пункте <em>Interface</em> и <strong>SwiftUI App</strong> в пункте <em>Life Cycle</em>. В качестве языка должен быть выбран <strong>Swift</strong>. <em>Core Data</em> и <em>тесты</em> нам не понадобятся. Ваш экран должен быть похож (кроме информации о разработчике) на скриншот ниже:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxWiFMZG2iyUZGcAo1A2ow.png" /><figcaption>Поле Team можно не заполнять — оно предназначено для запуска приложений на реальном устройстве</figcaption></figure><p>На следующем экране нажимаем кнопку <strong>Create</strong> и в итоге получаем экран с новым проектом, который в общем-то уже является самостоятельным приложением. Вы можете его запустить, используя комбинацию клавиш <strong>Cmd+R</strong>,<strong> </strong>и убедиться, что приложение рабочее.</p><p>У вас откроется файл <strong>ContentView.swift</strong>, в котором уже будет написан некоторый код. Приложение Hello world, конечно, рабочее, но мы же хотим зажечь костры рябин, помните? Тогда перед строчкой <em>struct ContentView_Previews</em> срочно следующий код:</p><pre><strong>struct</strong> Sheet: View {</pre><pre><strong>  var</strong> body: <strong>some</strong> View {</pre><pre>    HStack {</pre><pre>      Spacer()</pre><pre>      VStack {</pre><pre>        Spacer()</pre><pre>        Text(&quot;3&quot;)</pre><pre>          .font(.largeTitle)</pre><pre>          .foregroundColor(.red)</pre><pre>        Text(&quot;сентября&quot;)</pre><pre>          .font(.title)</pre><pre>          .foregroundColor(.red)</pre><pre>        Spacer()</pre><pre>      }</pre><pre>      Spacer()</pre><pre>    }</pre><pre>    .background(Color.white)</pre><pre>    .cornerRadius(15)</pre><pre>    .shadow(radius: 10)</pre><pre>  }</pre><pre>}</pre><p>Давайте разбираться, что же тут написано. Если вы хоть раз имели дело со SwiftUI, то вы наверняка знаете, что весь интерфейс теперь представляет собой структуры (в отличие от UIKit, где используются как в известной соцсети классы). И вот мы создаём структуру календарного листа, где пишем заветную дату красным цветом (за что отвечают структуры <strong>Text</strong> и модификаторы <strong>.foregroundColor </strong>соответственно), добавляем симпатичные эффекты вроде закруглённых краёв и тени. Наш лист закончен и красив, давайте же заменим код внутри переменной <em>body</em> в <em>ContentView</em> на следующие две строчки:</p><pre>Sheet()<br>  .padding()</pre><p>Запускаем!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-e4ZTM1H43SSAH8lkfXLA.png" /><figcaption>Также можно использовать preview, чтобы не запускать симулятор</figcaption></figure><p>Ну что, переворачиваем?</p><p>Для начала неплохо бы завести переменную, которая будет отвечать за переворачивание сего безобразия. Сделать это надо будет в <em>ContentView</em> над <em>var body</em>:</p><pre>@State <strong>private</strong> <strong>var</strong> isUp = <strong>true</strong></pre><p>Теперь к самому повороту. В SwiftUI есть модификатор <strong>.rotation3DEffect</strong>, как раз поворачивающий <em>View</em> в заданных плоскостях на заданное количество градусов. Вставьте его прямо перед строчкой <em>.padding()</em>:</p><pre>.rotation3DEffect(Angle(degrees: isUp ? 0 : 180), axis: (x: 1.0, y: 0.0, z: 0.0))</pre><p>Параметры модификатора довольно логичны: угол поворота и оси поворота. И если с осью всё более или менее понятно, то про угол стоит объяснить отдельно. Конструкция <em>isUp ? 0 : 180</em> называется <strong>тернарный оператор</strong> и представляет собой короткую версию оператора<em> if</em>:</p><pre>if isUp { return 0 } else { return 180 }</pre><p>Такой оператор используется очень часто, потому что разительно сокращает количество кода.</p><p>Логично, что для поворота надо менять значение нашей переменной isUp. Давайте сделаем так, чтобы оно менялось по клику на лист. Для этого следующей же строчкой после .rotation3DEffect вставьте следующий код:</p><pre>.onTapGesture {</pre><pre>  withAnimation {</pre><pre>    isUp.toggle()</pre><pre>  }</pre><pre>}</pre><p>Чем хорош SwiftUI, так это простотой создания анимаций. Достаточно обернуть любой код в конструкцию withAnimation { }, и всё произойдёт будто по воле волшебной палочки. И вот мы запускаем, нажимаем… и видим что-то странное:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVbmf4kNPSJEkAQnobCYKw.png" /><figcaption>Тем временем в Австралии :)</figcaption></figure><p>Оно, конечно, тоже третье сентября, но какое-то неродное. Спокойно! Сейчас будем избавляться от этой австралийщины! Для этого внутри нашего Sheet мы введём переменную (над <em>var body</em>), которая будет сообщать состояние календаря:</p><pre>let isUp: Bool</pre><p>Чтобы как-то адекватно отразить наш текст (хотя он и так неотразим!), обернём оба Text в ещё один VStack, а после него вставим до боли знакомую нам конструкцию rotation3DEffect:</p><pre>VStack {</pre><pre>  Text(&quot;3&quot;)</pre><pre>    .font(.largeTitle)</pre><pre>    .foregroundColor(.red)</pre><pre>  Text(&quot;сентября&quot;)</pre><pre>    .font(.title)</pre><pre>    .foregroundColor(.red)</pre><pre>}.rotation3DEffect(Angle(degrees: isUp ? 0 : 180), axis: (x: 1.0, y: 0.0, z: 0.0))</pre><p>Запускаем ещё раз… И всё работает, ура! Но вот возвращающийся календарь не так хорош, как перевёрнутый в нужную сторону столько раз. Давайте немного исправим этот недочёт. Для этого введём ещё одну переменную и расположим её прямо под объявлением isUp в ContentView:</p><pre>@State <strong>private</strong> <strong>var</strong> sheetRotation = 0.0</pre><p>Затем в rotation3DEffect меняем наш тернарный оператор на новую переменную, а в onTapGesture прибавляем 180 при каждом нажатии кнопки. Получится такой код:</p><pre>.rotation3DEffect(Angle(degrees: sheetRotation),axis: (x: 1.0, y: 0.0, z: 0.0))</pre><pre>.onTapGesture {</pre><pre>  withAnimation {</pre><pre>    sheetRotation += 180.0</pre><pre>    isUp.toggle()</pre><pre>  }</pre><pre>}</pre><p>И вот теперь всё работает так, как надо! А значит — Михаил Захарович будет доволен. Но где же обещанные костры рябин, спросите вы?</p><p>Сейчас будут! Скачиваете фото отсюда: <a href="https://unsplash.com/photos/kOgg4aUc9lc">https://unsplash.com/photos/kOgg4aUc9lc</a></p><p>В левой части Xcode переходите в Assets.xcassets и перетаскиваете на белый список файлов слева (где есть AccentColor и AppIcon) нашу картинку:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Br5FrahUOBi8Si7JzrPsRQ.png" /></figure><p>Не забудьте переименовать её в “ryabina”, дважды кликнув по названию.</p><p>Дальше переходим обратно в ContentView.swift и в структуре Sheet прямо над первым Text в VStack вставляем такой код:</p><pre>Image(&quot;ryabina&quot;)</pre><pre>  .resizable()</pre><pre>  .aspectRatio(contentMode: .fit)</pre><pre>  .padding()</pre><p>В него мы вставляем картинку и умещаем её в рамки приличия, то есть в рамки нашего листочка. С небольшим отступом, конечно же.</p><p>И вот теперь мы точно всё. Существует много различных способов улучшить это простенькое приложение, так что вперёд — к изучению SwiftUI!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Okba3VzPPcywPKxmd-o3Fg.png" /></figure><p>Всем теплоты и ласки, друзья!</p><p>А готовый проект вы можете найти на моём GitHub: <a href="https://github.com/iamalexantonov/RotatingCalendar">https://github.com/iamalexantonov/RotatingCalendar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6faea96c0ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving Christmas mood with Vision]]></title>
            <link>https://iamalexantonov.medium.com/saving-christmas-mood-with-vision-3eb41e97a3e1?source=rss-ee36fdf90367------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb41e97a3e1</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[vision]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[create-ml]]></category>
            <dc:creator><![CDATA[Alexey Antonov]]></dc:creator>
            <pubDate>Sun, 03 Jan 2021 12:59:03 GMT</pubDate>
            <atom:updated>2021-01-03T12:59:03.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhuruUNvD6lhtyHGX5CIOA.jpeg" /><figcaption>(c) Rodion Kutsaev — Unsplash</figcaption></figure><p>I love winter holidays because of the special mystery mood these days. That’s why right after the 1st of January I tried to make this time last a bit longer. And now I want to share with you the way I did it, also introducing machine learning with Swift and Vision framework.</p><p>Let’s start! First, create a blank UIKit (<em>Storyboard</em>) project in Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5E8wTKYqjfsyQPDaTdAUaQ.png" /><figcaption>Name it with a nice title</figcaption></figure><p>Our goal is to make the app that differs Christmas tree from other stuff. For that particular reason we will train our machine learning model. But first, let’s find our content for the training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-w-3YkLvOhBdRN4bkxeww.png" /><figcaption>I’ve searched for “Christmas tree” (for detection), “wall”, “street”, “tree” (for other stuff) in Google</figcaption></figure><p>After downloading some images (50 — 100 images for each category is quite good) for training I split all of them into this folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3vQNXzYAMhmH78_A-sh6g.png" /></figure><p>Folder “<strong>train</strong>” contains two folders with two types of images: Christmas tree and other stuff. I also created test folder with images for testing (usually 20% of training images is enough for testing). Next, let’s create our first ML model. For that, open <strong>CreateML</strong> app that you can access from the menu: <strong>Xcode -&gt; Open Developer Tool -&gt; CreateML</strong>. You will see a dialogue for creating new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyNtLKNdk7yz-hCqV24l7g.png" /></figure><p>Choose a default “<strong>Image Classification</strong>” template, click “<em>Next</em>” button, enter the name of your classifier and create a project. The main screen is “<strong>Data</strong>”, and here you should choose your “<em>train</em>” folder in “<strong>Training Data</strong>” block and “<em>test</em>” folder for “<strong>Testing Data</strong>” block. I also selected <em>Crop</em> option just to be sure that it will detect a part of the Christmas tree. When you finish this, click “<strong>Train</strong>” button in upper left corner of the main screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1TtHw8kkMwuGdQSdItCow.png" /></figure><p>Here it is! Now your model is trained and works. Want to try? Well, click <strong>Preview</strong> tab on the main screen and drag-n-drop couple images into the screen. You will see class name (which is a name of the folder with images) and confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoHSOqojrqIWr4VsE-gsOw.png" /><figcaption>Nice view, but doesn’t contain Christmas tree</figcaption></figure><p>Now, when you are sure that it works well, go to <strong>Output</strong> tab and click <strong>Get</strong> button to save your model. Add it to your Xcode project like you add all existing files and don’t forget to check the target and “<em>Copy items if needed</em>”. Ready to code? Well, wait… Let’s make some changes in settings and create a UI in Storyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6xTE9G3-YE3aOGp8BiurA.png" /><figcaption>Leave only iPhone and Portrait orientation checked</figcaption></figure><p>We will place <strong>UILabel</strong>, <strong>UIImageView</strong> and <strong>UIButton</strong> on the screen. Do all the work with <strong>AutoLayout</strong> and connect <em>Label</em> (outlet), <em>Button</em> (action) and <em>ImageView</em> (outlet) to your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrVUOIE-t_8e_gdghryTxg.png" /><figcaption>For the label I used Chalkduster font with size of 20pt and red color</figcaption></figure><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> classificationLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> previewView: UIImageView!</pre><pre><strong>@IBAction</strong> <strong>func</strong> oneMoreTry(<strong>_</strong> sender: <strong>Any</strong>) {</pre><pre>}</pre><p>On the top of <strong>ViewController</strong> let’s import <strong>Vision</strong> and <strong>AVFoundation</strong> frameworks:</p><pre><strong>import</strong> Vision</pre><pre><strong>import</strong> AVFoundation</pre><p>And the first we should do is to show camera capture dialogue. For that, we will use <strong>UIImagePickerController</strong> with camera source type:</p><pre><strong>private</strong> <strong>func</strong> setupCamera() {</pre><pre><strong>  let</strong> cameraPicker = UIImagePickerController()</pre><pre>  cameraPicker.sourceType = .camera</pre><pre>  cameraPicker.delegate = <strong>self</strong></pre><pre><strong>  self</strong>.present(cameraPicker, animated: <strong>true</strong>, completion: {})</pre><pre>}</pre><p>To transmit shot to the main <em>ViewController</em>, we will make it a <strong>delegate</strong> of the <strong>UIImagePickerController</strong>. And only after that we will present it modally.</p><p>Let’s write a boilerplate <strong>extension</strong> in order to make this <em>ViewController</em> a picker’s <em>delegate</em>:</p><pre><strong>extension</strong> ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { }</pre><p>Let’s call this function from the method of the <em>View Controller life cycle</em> called <strong>viewDidAppear</strong>. As it’s inherited from the base <em>UIViewController</em> class (OOP theory understanding is still one of the basic programming skills), we call first its superclass method:</p><pre><strong>override</strong> <strong>func</strong> viewDidAppear(<strong>_</strong> animated: Bool) {</pre><pre><strong>  super</strong>.viewDidAppear(animated)</pre><pre>...</pre><p>You may think that we can call <strong>setupCamera()</strong> function right below it, but… There’s a special thing in iOS that is called feature authorization. We should allow usage of camera, so let’s go first to<strong> Info.plist</strong> file and add there one property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwes221oNKxWuoDKzbsAHQ.png" /><figcaption>You can write any description you want</figcaption></figure><p>Then, under calling superclass <em>viewDidAppear</em> method, let’s write this chunk of code:</p><pre><strong>switch</strong> AVCaptureDevice.authorizationStatus(for: .video) {</pre><pre><strong>  case</strong> .authorized:</pre><pre><strong>    self</strong>.setupCamera()</pre><pre><strong>  case</strong> .notDetermined:</pre><pre>    AVCaptureDevice.requestAccess(for: .video) { granted <strong>in</strong></pre><pre><strong>      if</strong> granted {</pre><pre><strong>        self</strong>.setupCamera()</pre><pre>      }</pre><pre>    }</pre><pre><strong>  default</strong>:</pre><pre><strong>    return</strong></pre><pre>}</pre><p>We will call <strong>setupCamera()</strong> function only if the user authorizes app to use the camera. Below we can also set up the default label text to tell the user what to do:</p><pre><strong>self</strong>.classificationLabel.text = &quot;Find a Christmas tree&quot;</pre><p>Connect your iPhone, hit “Run”, and you can see camera dialogue appearing after the app shows UI. Want to see the image in our <em>ImageView</em>? Okay! Let’s implement <em>UIImagePickerController</em> delegate method to take user’s picture to the <em>ViewController</em>. In the extension we wrote earlier now create this method:</p><pre><strong>func</strong> imagePickerController(<strong>_</strong> picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : <strong>Any</strong>]) {</pre><pre><strong>let</strong> photo = info[UIImagePickerController.InfoKey.originalImage] <strong>as</strong>! UIImage</pre><pre><strong>self</strong>.previewView.image = photo</pre><pre>dismiss(animated: <strong>true</strong>, completion: <strong>nil</strong>)</pre><pre>}</pre><p>Rerun the app and try to use the photo taken in the dialogue. But after selecting the photo the dialogue opens again. Why is it happening?</p><p>The reason is that the <strong>viewDidAppear</strong> function is called every time the view shows, even after the modal view hides. So we can make a small hack to prevent it from reopening. Right after <em>IBOutlets</em> create a variable:</p><pre><strong>var</strong> isLoading = <strong>true</strong></pre><p>And then wrap authorization code into condition:</p><pre><strong>if</strong> isLoading {</pre><pre><strong>  switch</strong> AVCaptureDevice.authorizationStatus(for: .video) {</pre><pre><strong>    case</strong> .authorized:</pre><pre><strong>      self</strong>.setupCamera()</pre><pre><strong>    case</strong> .notDetermined:</pre><pre>      AVCaptureDevice.requestAccess(for: .video) { granted <strong>in</strong></pre><pre><strong>        if</strong> granted {</pre><pre><strong>          self</strong>.setupCamera()</pre><pre>        }</pre><pre>      }</pre><pre><strong>    default</strong>:</pre><pre><strong>      return</strong></pre><pre>  }</pre><pre>  isLoading = <strong>false</strong></pre><pre>}</pre><p>Now it will be presented only after the app starts. And to retake a photo call <em>setupCamera()</em> function in the <strong>oneMoreTry</strong> method of button click:</p><pre><strong>@IBAction</strong> <strong>func</strong> oneMoreTry(<strong>_</strong> sender: <strong>Any</strong>) {</pre><pre>  setupCamera()</pre><pre>}</pre><p>Although we can take photos and show them in <em>UIImageView</em>, it’s still not what we want in the first place. I’m sure you can’t wait for diving into Vision framework. Let’s create a <strong>VNRequest</strong> — request for image classification that will use our model. Write this code after creating <em>isLoading</em> variable:</p><pre><strong>var</strong> classificationRequest: VNRequest {</pre><pre><strong>  let</strong> model = <strong>try</strong>! VNCoreMLModel(for: ChristmasTreeClassifier().model)</pre><pre><strong>  let</strong> request = VNCoreMLRequest(model: model, completionHandler: { [<strong>weak</strong> <strong>self</strong>] request, error <strong>in</strong></pre><pre><strong>  self</strong>?.processClassifications(for: request, error: error)</pre><pre>})</pre><pre> request.imageCropAndScaleOption = .centerCrop</pre><pre><strong>  return</strong> request</pre><pre>}</pre><p>“Import” our model into Vision and create the request that uses our model and calls <strong>processClassifications</strong> function in our <em>ViewController</em>. Then set the option for cropping the photo and return the request as it is a computed variable.</p><p>The function <strong>processClassifications</strong> takes our <strong>VNRequest</strong> and error and sees the results of the image classification in the <em>main queue</em> (as we will update the UI). It takes the type of the result to the array of <strong>VNClassificationObservation</strong> to get all necessary data and checks the most confident type:</p><pre><strong>func</strong> processClassifications(for request: VNRequest, error: Error?) {</pre><pre>  DispatchQueue.main.async {</pre><pre><strong>    guard</strong> <strong>let</strong> results = request.results <strong>else</strong> {</pre><pre><strong>      self</strong>.classificationLabel.text = &quot;Unable to classify image.\n\(error!.localizedDescription)&quot;</pre><pre><strong>      return</strong></pre><pre>    }</pre><pre><strong>    if</strong> <strong>let</strong> classifications = results <strong>as</strong>? [VNClassificationObservation] {</pre><pre><strong>      if</strong> classifications.first?.identifier == &quot;Christmas Tree&quot; &amp;&amp; classifications.first!.confidence &gt; 0.9 {</pre><pre><strong>        self</strong>.classificationLabel.text = &quot;This is a Christmas Tree! HO-HO-HO!&quot;</pre><pre>      } <strong>else</strong> {</pre><pre><strong>        self</strong>.classificationLabel.text = &quot;That&#39;s not a Christmas tree&quot;</pre><pre>      }</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><p>Based on the classification result, the function updates the label. But how can we trigger the Vision framework? Well, here we need to add some more code to <em>UIImagePickerControllerDelegate</em> function. After getting user’s photo insert the following:</p><pre>...</pre><pre><strong>let</strong> photo = info[UIImagePickerController.InfoKey.originalImage] <strong>as</strong>! UIImage</pre><pre>DispatchQueue.global(qos: .userInitiated).async {</pre><pre><strong>  let</strong> handler = VNImageRequestHandler(cgImage: photo.cgImage!, orientation: .up, options: [:])</pre><pre><strong>  do</strong> {</pre><pre><strong>    try</strong> handler.perform([<strong>self</strong>.classificationRequest])</pre><pre>  } <strong>catch</strong> {</pre><pre>    print(&quot;Failed to perform classification.\n\(error.localizedDescription)&quot;)</pre><pre>  }</pre><pre>}</pre><pre>...</pre><p>In a <em>background queue</em> we run <strong>VNImageRequestHandler</strong> by providing it with the photo, correct orientation and created request. Well, now we are ready. Run the app and try it out!</p><p>Nice, isn’t it? Let’s add even more! Do you like Santa telling “Ho-ho-ho”? Get a royalty-free sound effect (like that one: <a href="https://freesound.org/people/Intimidated/sounds/258227/">https://freesound.org/people/Intimidated/sounds/258227/</a>), add it to the project and append an <em>AVAudioPlayer</em>. On the top of our <em>ViewController</em> insert the following code:</p><pre><strong>var</strong> audioPlayer: AVAudioPlayer?</pre><p>In the end of the <em>viewDidAppear</em> function now put in the player initialization:</p><pre><strong>do</strong> {</pre><pre><strong>  try</strong> AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)</pre><pre><strong>  try</strong> AVAudioSession.sharedInstance().setActive(<strong>true</strong>)</pre><pre><strong>  let</strong> path = Bundle.main.path(forResource: &quot;hohoho&quot;, ofType:&quot;wav&quot;)!</pre><pre><strong>  let</strong> url = URL(fileURLWithPath: path)</pre><pre>  audioPlayer = <strong>try</strong> AVAudioPlayer(contentsOf: url)</pre><pre>  audioPlayer?.prepareToPlay()</pre><pre>} <strong>catch</strong> {</pre><pre>  print(error.localizedDescription)</pre><pre>}</pre><p>That is how we set up the player and loaded a sound. Now it’s time to modify <strong>processClassifications</strong> function to add an audio message. Write this code right after changing label to the greeting:</p><pre><strong>...<br>self</strong>.classificationLabel.text = &quot;This is a Christmas Tree! HO-HO-HO!&quot;</pre><pre><strong>if</strong> !(<strong>self</strong>.audioPlayer?.isPlaying ?? <strong>true</strong>) {</pre><pre><strong>  self</strong>.audioPlayer?.play()</pre><pre>}<br>...</pre><p>Indeed, we are finished and full of mysterious Christmas mood. Share it with your friends! Merry Christmas and Happy New Year! 🎅🎄</p><p>P.S. You can find all the code here: <a href="https://github.com/iamalexantonov/Hohoho">https://github.com/iamalexantonov/Hohoho</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb41e97a3e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Staying safe and having fun with ARKit]]></title>
            <link>https://iamalexantonov.medium.com/staying-safe-and-having-fun-with-arkit-80af2fd14448?source=rss-ee36fdf90367------2</link>
            <guid isPermaLink="false">https://medium.com/p/80af2fd14448</guid>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[arkit]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Alexey Antonov]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 17:21:27 GMT</pubDate>
            <atom:updated>2020-11-19T17:21:27.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbYPhnugwDX-5rX_pzj-Mw.png" /></figure><p>A lot of people in the world are worrying about coronavirus and staying safe in the current situation. Let’s try to use ARKit to tell others how important it is to wear a mask.</p><p>Let’s dive in. Create new <strong>iOS App</strong> with <strong>Storyboard</strong>-based UI. But before coding download a 3D-model: <a href="https://www.turbosquid.com/3d-models/n95-mask-3d-model-1574740">https://www.turbosquid.com/3d-models/n95-mask-3d-model-1574740</a> (don’t worry — it’s free!).</p><p>Add new file to the project a new <strong>SceneKit Catalog</strong> and name it <em>Models.scnassets</em>. Then, add there <em>.mtl</em>, <em>.obj</em> and <em>.png</em> files. Leave png file name as it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCa455AmopMO4IrGU78Kjw.png" /></figure><p>In storyboard <em>Document outline</em> select <strong>View</strong> and in <em>Identity Inspector</em> change class to <strong>ARSCNView</strong> (like on a screenshot above). Immediately after that connect this view to the <strong>ViewController</strong>.</p><p>So, now it’s time to code. Open <em>ViewController.swift</em> and add<strong> ARKit</strong> on the top:</p><pre><strong>import</strong> ARKit</pre><p>Then implement viewDidLoad(), viewWillAppear() and viewWillDisappear() methods to add a support of ARKit:</p><pre><strong>class</strong> ViewController: UIViewController {</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> sceneView: ARSCNView!</pre><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>  super</strong>.viewDidLoad()</pre><pre><strong>  if</strong> !ARFaceTrackingConfiguration.isSupported {</pre><pre>    fatalError(&quot;Face tracking is not supported&quot;)</pre><pre>  }</pre><pre>  sceneView.delegate = <strong>self</strong></pre><pre>}</pre><pre><strong>override</strong> <strong>func</strong> viewWillAppear(<strong>_</strong> animated: Bool) {</pre><pre><strong>  super</strong>.viewWillAppear(animated)</pre><pre>  sceneView.session.run(ARFaceTrackingConfiguration())</pre><pre>}</pre><pre><strong>override</strong> <strong>func</strong> viewWillDisappear(<strong>_</strong> animated: Bool) {</pre><pre><strong>  super</strong>.viewWillDisappear(animated)</pre><pre>  sceneView.session.pause()</pre><pre>  }</pre><pre>}</pre><p>As you can see the app checks availability of face tracking API and sets our <em>ViewController</em> as a <strong>delegate</strong> of a <em>sceneView</em>. Then, it controls the session run and pause.</p><p>Of course, that’s not all. As we told app that this ViewController will be a delegate for sceneView, let’s implement it too:</p><pre><strong>extension</strong> WearMaskViewController: ARSCNViewDelegate {</pre><pre><strong>  func</strong> renderer(<strong>_</strong> renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -&gt; SCNNode? {</pre><pre><strong>    if</strong> <strong>let</strong> url = Bundle.main.url(/service/forresource: &quot;mask&quot;, withExtension: &quot;obj&quot;, subdirectory: &quot;Models.scnassets&quot;),</pre><pre><strong>    let</strong> overlay = SCNReferenceNode(url: url) {</pre><pre>      overlay.load()</pre><pre><strong>      let</strong> node = SCNNode()</pre><pre>      node.addChildNode(overlay)</pre><pre><strong>      return</strong> node</pre><pre>    } <strong>else</strong> {</pre><pre><strong>      return</strong> <strong>nil</strong></pre><pre>    }</pre><pre>  }</pre><pre>}</pre><p>The <em>renderer(_: nodeFor:)</em> method of <strong>ARSCNDelegate</strong> applies mask to your face. Our simplest version of the app is almost ready. The only thing left is to adjust scale and position of mask. Your can do it by changing these properties of <em>mask.obj</em> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5b_tYZtyukU-bJm92ZOaJg.png" /><figcaption>You can see that my object has an offset, but Xcode doesn’t show it. In my experience the scale should be about 0.02 for each axis and also a little bit to the right and bottom</figcaption></figure><p>Think it works? Yes. But no. Remember: Apple respects our privacy, so we should add a description to the <strong>Privacy — Camera Usage Description</strong> key of <em>Info.plist</em> file. And… that’s it!</p><p>Hit run, have fun, improve it, stay safe and wear a mask! ✌️😷</p><p>P.S. All code is available on GitHub: <a href="https://github.com/antonoff/WearMask">https://github.com/antonoff/WearMask</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80af2fd14448" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Instagram-like place selection with SwiftUI]]></title>
            <link>https://iamalexantonov.medium.com/creating-instagram-like-place-selection-with-swiftui-e3ed317f0079?source=rss-ee36fdf90367------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ed317f0079</guid>
            <category><![CDATA[core-location]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Alexey Antonov]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 13:44:21 GMT</pubDate>
            <atom:updated>2020-10-27T15:44:57.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*kqL1PlWVIhtAaFMLEavdzA.png" /></figure><p>Let’s pretend that you’re writing an app with SwiftUI that will need to provide nearby places with filtering option sorted by distance. Just like one in your Instagram. You think it’s hard? Let’s get our hands dirty and ruin this myth.</p><p>Create a new iOS App that uses SwiftUI and open <em>ContentView.swift</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5Dledwe0jc7WSUkyYyzPg.png" /></figure><p>Get rid of the <strong>Text</strong> component and add the <strong>TextField</strong> component. TextField requires two parameters: <em>title</em> (that in other words is a placeholder) and <em>text</em> (that will contain entered text). As text parameter has type of <em>Binding&lt;String&gt;</em>, we should create a variable to store our value first. So, your code should look like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VoZyAUWpGG_-ENrf_JADA.png" /></figure><p>To be sure that it works, put your <strong>TextField</strong> component into a <strong>VStack</strong> and insert after this text field a <strong>Text</strong> component with a value of <em>searchText</em> variable. Now, when you type into the text field, you will see the result immediately appearing below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWoHDYrxLEQZ1QyzyiC2Ew.png" /><figcaption>Also you can add some padding to a VStack to make it more visible</figcaption></figure><p>Then, when we made this text field work, let’s dive into some adding. So, first we need to create a model. Go and create a new <em>.swift</em> file (<strong>not SwiftUI view!</strong>). I named it <em>Place.swift</em>, but it doesn’t matter how you will call it.</p><p>In a new file <strong>import CoreLocation</strong> framework right under <em>import Foundation</em> line. That will be needed for giving coordinates to our places. Let’s begin and create a struct called <em>Place</em>. It will have only two properties: the title of the place (that has <em>String</em> type) and the location of the place (that has <em>CLLocation</em> type). Then, let’s create an <em>array</em> right under the struct and fill it with some places:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwT8Yk16e1YhVv_9zWj2VA.png" /></figure><p>Moving back to <em>ContentView.swift</em> file: creating a list of places. For that reason, get rid of the <strong>Text</strong> component and insert a <strong>List</strong> component that will contain our <em>places</em> array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iepoGiqGDPqYtjWA4yWV9Q.png" /><figcaption>This list contains titles of places, but at the moment something is wrong</figcaption></figure><p>The code was quite correct, but something went wrong. The error occurred because the <strong>List</strong> component requires the array items needed to confirm to <strong>Identifiable</strong> protocol. It’s necessary to differ items from each other. But we can make a small ‘hack’ as it’s not our final solution. We will add <em>id: \.title</em> parameter to make the items’ titles identify it. Woo-hoo, now it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1WitiDoqzVxcKGDEKaAdw.png" /></figure><p>But honestly we won’t need to show a coordinate, so now we will go back and create another struct called <em>Location </em>below the <em>Place</em> struct. This struct is going to confirm to <strong>Identifiable</strong> protocol and have title and distance fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wrKiex0COwilc6AQcGpVw.png" /></figure><p>Thus, when the model is ready, let’s go and create another .swift file. Now it’s a <em>ViewModel</em> that will contain all our <strong>CoreLocation</strong> stuff. So, we also <strong>import CoreLocation</strong> under Foundation and create a class called <em>ViewModel</em>. It will be a subclass of <strong>NSObject</strong> and confirm to protocol <strong>ObservableObject</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*PfK5Xq8Zlbimyx7DzbKePA.png" /></figure><p>Next, it’s time to add an instance of <strong>CLLocationManager</strong>, that will do all the geolocation work. As a result, it will be a <em>private</em> constant as we won’t use it outside our class. And right below it we add an initialiser of the class, when we set up the geolocation stuff:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*T4bfCvRrDdmMZiMxhcOiDA.png" /><figcaption>As our class is a subclass of NSObject, we need to override a parent init() method and call super.init()</figcaption></figure><p>Here, we ask for permission to use the geolocation when app works in a foreground, tell that our class will be a delegate for CLLocationManager and finally start listening for location updates. As we promised that this class will be a delegate for our location manager, let’s write an extension for our class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rp9xZgv2KrjnCIEtlisFJQ.png" /><figcaption>I know that I could chain two last lines of method, but I decided to make it the more understandable way</figcaption></figure><p>We need to implement only one method (just for this small purpose), that is called when the phone updates geolocation. As you could notice before, the distance of our struct <em>Location</em> is <em>Optional</em>, because sometimes the GPS module can’t receive current geolocation (when the user is in subway area or somewhere the location is unavailable). That’s why it’s reasonable to leave it optional. Hence, if we can’t get new geolocation we just exit the function. In case we have location, we clean the array with old distances, sort places according new values and fill the locations array with necessary data. We also want to show the distance in kilometres, so divide the value by 1000.</p><p>Now we can see it in our app. Just add our <em>viewModel</em> as an <strong>ObservedObject</strong> and change the <strong>List</strong> component to accept <em>viewModel.locations</em> array without any id parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*q_crfoGNK3EnG1ih8Qt7GA.png" /></figure><p>Nevertheless we still can’t filter it by name, so let’s apply filter function to our parameter of <strong>List</strong> component:</p><p><strong>List(viewModel.locations.filter { $0.title.hasPrefix(searchText) })</strong></p><p>Now if you build and run the app on Simulator or real device, you will see something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEoa5rkBX9T-qzui4lC1uA.png" /><figcaption>Yes, I am obsessed with new iPhone 12 mini, so let it be at least on a Simulator 😀</figcaption></figure><p>In the end it’ll be nice to have a fancy row with a distance to the location, so let’s create another SwiftUI view just under the <em>ContentView</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wLIyg5gaZMDlTbsrpB0cA.png" /><figcaption>The specifier allows us to cut long numbers in a string</figcaption></figure><p>Now we can replace Text component in our list with <em>PlaceRaw</em> filling it with place parameter and see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bM7MOzOtAJt0oLHk1Ew_cw.png" /><figcaption>Hooray! We did it! 🎊🎉</figcaption></figure><p>Now you’re done! Thanks for reading! Let’s go and have some pizza nearby 🍕!</p><p>P.S. All code is available on GitHub: <a href="https://github.com/antonoff/Places">https://github.com/antonoff/Places</a></p><p>P.P.S. I want to thank the Apple Foundation students team NAPPoletan for their amazing work and inspiring me to write this tutorial!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ed317f0079" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>