<?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 Baha Abisheva on Medium]]></title>
        <description><![CDATA[Stories by Baha Abisheva on Medium]]></description>
        <link>https://medium.com/@bahalek?source=rss-3a9c66959e30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nT3bvogxXHliDN_19esgBw.jpeg</url>
            <title>Stories by Baha Abisheva on Medium</title>
            <link>https://medium.com/@bahalek?source=rss-3a9c66959e30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:50:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bahalek/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[Getting iOS device logs using idevicesyslog]]></title>
            <link>https://medium.com/@bahalek/getting-ios-device-logs-using-idevicesyslog-dfd806f56d27?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfd806f56d27</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[idevicesyslog]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 22:22:57 GMT</pubDate>
            <atom:updated>2025-03-03T03:19:05.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HA3h_AerZabId_w_" /><figcaption>Photo by <a href="https://unsplash.com/@vmxhu?utm_source=medium&amp;utm_medium=referral">Szabo Viktor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article will show how to use command-line tool idevicesyslog to capture and display syslog messages from iOS devices. This is particularly useful when you need to monitor and analyze system logs from iOS devices. It can help you debug how your app interacts with the OS, how your app behaves while it is in background, network request logs, if your app connects to different hardware etc. idevicesyslog can also be incorporated into scripts for automated testing or monitoring purposes.</p><h3>Prerequisites</h3><p>Make sure you have Xcode and homebrew installed. Use homebrew to install libimobiledevice , it bundles a bunch of command line utilities including idevicesyslog. For more info check <a href="https://github.com/libimobiledevice/libimobiledevice">their repo</a>. To install run this in your Terminal:</p><pre>brew install libimobiledevice</pre><h3>Getting device logs</h3><p><strong>Step 1.</strong> Connect your iOS device to your Mac and open the Terminal</p><p><strong>Step 2. Run </strong><strong>idevicesyslog.</strong></p><p>In the Terminal, run the following command to start capturing syslog messages:</p><pre>idevicesyslog</pre><p><strong>Note 1: </strong>if you have more than 1 device connected to the Mac you will need to include device udid when you run idevicesyslog. To find your device udid you can run idevice_id -l .</p><pre>idevicesyslog -u &lt;device udid&gt;</pre><p><strong>Note 2:</strong> You can use -m option in idevicesyslog to only print messages that contain your app name/bundle id or any other string you are interested in.</p><pre>idevicesyslog -m &quot;YourAppName OR specific message&quot;</pre><p><strong>Step 3. Launch the App on Your iOS Device and analyze the syslog output.</strong></p><p>On your connected iOS device, launch the app that you want to debug. You will see a stream of syslog messages in your Terminal. Look for log entries related to the app you just launched.</p><h3>Conclusion</h3><p>idevicesyslog is a powerful tool, it provides a command-line interface to access system logs. You can also use Xcode Instruments and other specialized tools provided by Apple’s development environment for more comprehensive profiling, debugging, and performance analysis.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfd806f56d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up JS bridge between your webpage and WKWebview in your iOS app]]></title>
            <link>https://medium.com/@bahalek/setting-up-js-bridge-between-your-webpage-and-wkwebview-in-your-ios-app-4ec8ca8230f7?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec8ca8230f7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webview]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 21:32:49 GMT</pubDate>
            <atom:updated>2025-03-03T03:18:12.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1dmTRU6sXy8w8TfF" /><figcaption>Photo by <a href="https://unsplash.com/@ion66574?utm_source=medium&amp;utm_medium=referral">Ion (Ivan) Sipilov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Nowadays a lot of apps prefer to display content using a webview. This creates a need for webviews to try and act like native views. For that, there has to be a way for the web page to communicate with the app and vice versa. This can be done using a JavaScript bridge.</p><h3>What is a JS bridge?</h3><p>A JavaScript bridge acts like a communication channel for two-way data exchange between the web content and the native app. Both iOS and Android webviews support communicating through JS bridges. In this tutorial we will focus on iOS setup.</p><h3>Setting up the JS bridge on iOS</h3><p>To display your web content in the app, you will need an instance of WKWebView setup and shown to the user in one of your screens. For the webview:</p><ul><li>Define a <a href="https://developer.apple.com/documentation/webkit/wkscriptmessagehandler">WKScriptMessageHandler</a> that will receive messages from JavaScript and process the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKoPuyGi4Go2ew29s7VYQA.png" /></figure><ul><li>Add the script message handler to the user content controller that’s in webview’s configuration. The name of the message handler is important, so that you can make sure you are only processing data that was intended for your message handler.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPqE1YCRQkoSbYqHPsasVQ.png" /></figure><h3>Communicating with JavaScript</h3><p>Now that the bridge is setup on the native side, you can start communicating with JavaScript from your webpage and back.</p><ul><li>To inject JS from native into webpage, use evaluateJavaScript method</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSWNP_KdnVSzjFYlAP9G9A.png" /></figure><ul><li>To send JS message from your webpage to native, post messages using a similar syntax as above in your JavaScript code</li></ul><pre>window.webkit.messageHandlers.myHandler.postMessage(&#39;Hello from JS!&#39;);</pre><h3>Conclusion</h3><p>This way you can greatly enhance interactivity for your native apps that use webviews. You can show native views based on JS messages from the webpage and signal your webpage when you need them to perform some JS on their side.</p><p>Happy coding!</p><p>P.S. If your app uses webviews a lot and you need a way to cache the webview content, checkout the story below:</p><p><a href="https://blog.devgenius.io/storing-wkwebview-content-for-offline-access-in-your-ios-app-b61daf528df2">Caching WKWebView content for offline access in your iOS app</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec8ca8230f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding unit test target for an existing Xcode project]]></title>
            <link>https://medium.com/@bahalek/adding-unit-test-target-for-an-existing-xcode-project-528eac6d89ba?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/528eac6d89ba</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 14:20:15 GMT</pubDate>
            <atom:updated>2025-03-03T03:19:21.321Z</atom:updated>
            <content:encoded><![CDATA[<p>If for some reason, when creating a new project you forgot to check the “Include Tests” button, fear not. Adding unit test target to an existing Xcode project is very simple. The steps below are done on Xcode 15.0.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvc95Fo52Pb9BF0p8sVJZg.png" /></figure><p>Once you have your project created without unit tests target, your project structure should look similar to the screenshot below. It will have a folder with your source code and resources and not much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjJAFVbOouIovtYBIfH3lQ.png" /></figure><p>To add a new target, go to File -&gt; New -&gt; Target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3p8KlEhgYSIAL0HIQok7w.png" /></figure><p>From the selection of targets choose either ui tests or unit tests and choose a name for your new target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQ1wFsfZznKEp3P3den9Cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18gwcERCiXtwEOTqBSSPmg.png" /></figure><p>And that should be it. After you hit “Finish” you will have your test target added to your project and you can start adding tests to your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcogklAH5B8WbRkCmdvfjg.png" /></figure><p>Happy unit testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=528eac6d89ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching WKWebView content for offline access in your iOS app]]></title>
            <link>https://blog.devgenius.io/storing-wkwebview-content-for-offline-access-in-your-ios-app-b61daf528df2?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61daf528df2</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[wkwebview]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 15:51:30 GMT</pubDate>
            <atom:updated>2025-03-03T03:18:48.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XsHF6s8yyqZAHhVk" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_source=medium&amp;utm_medium=referral">Jonathan Kemper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s connected world, providing offline access to web content is crucial for enhancing user experience and ensuring continuous access to information. In this article, we will explore how to store WKWebView content for offline access, enabling users to access web pages even without an internet connection. By leveraging web archiving, we can save web pages locally and load them when offline.</p><p>This tutorial has been written using Xcode14.3.</p><h4>Some theory first</h4><p><a href="https://developer.apple.com/documentation/webkit/wkwebview">WKWebView</a> is a powerful component in iOS development that allows the integration of web content into native applications. It offers a modern and efficient browsing experience, including support for web technologies like JavaScript, CSS, and HTML5.</p><p>In previous versions, when working with <a href="https://developer.apple.com/documentation/uikit/uiwebview">UIWebView</a>, developers could utilize NSURLProtocols and NSURLCache to store web view content. However, with the release of WKWebView, this functionality was no longer supported. Consequently, developers had to devise their own custom solutions to cache data for offline access. It wasn’t until iOS 14+ that Apple introduced built-in support for <a href="https://developer.apple.com/documentation/webkit/wkwebview/3650491-createwebarchivedata">creating web archives</a> directly within WKWebView.</p><p>Web archiving is a process of capturing and saving web content in a single file, commonly known as a web archive. It stores not only the HTML source but also associated resources such as images, stylesheets, and scripts. The web archive serves as a self-contained package that can be loaded and displayed offline.</p><p>Now we can dive into a hands on example for caching WKWebView content.</p><h4>WebArchiveDataManager</h4><p>To manage the storing and loading of web archive data, we will create a WebArchiveDataManager class. This class will handle interactions with the file system and the WKWebView component.</p><p>For now we will add functionality to create the folder where the archives will be stored and read from.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/640647d8cd5eff545732d18c48346780/href">https://medium.com/media/640647d8cd5eff545732d18c48346780/href</a></iframe><h4>Saving content</h4><p>Using the <a href="https://developer.apple.com/documentation/webkit/wkwebview/3650491-createwebarchivedata">createWebArchiveData</a> method of WKWebView, we can obtain the web archive data. By saving this data to the file system, we ensure it can be accessed later when offline. The code example below does exactly that in saveWebArchive function that will be added to our WebArchiveDataManager class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6189b4a1b361749ea9bb1089a018d6c8/href">https://medium.com/media/6189b4a1b361749ea9bb1089a018d6c8/href</a></iframe><h4>Loading content</h4><p>To load the web archive data back into the WKWebView, we use the load(_:mimeType:characterEncodingName:baseURL:) method. This method takes the archived data, the MIME type of the web archive, the character encoding name, and the baseURL. The code example below illustrates how to load the web archive data and display the content within the WKWebView.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6259e3f5fe217328f17d7d45f0ad7e3/href">https://medium.com/media/e6259e3f5fe217328f17d7d45f0ad7e3/href</a></iframe><h4>Using WebArchiveDataManager</h4><p>To use WebArchiveDataManager, simply create an instance in the class that has a reference to your webview and call save and load functions as needed. In my case I would check if we have internet connection and in case we are offline we would load the content from file, otherwise try to load the url.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb37d8d9b998d96dcd63e6d80bd9a41/href">https://medium.com/media/1bb37d8d9b998d96dcd63e6d80bd9a41/href</a></iframe><p>With the knowledge gained from this tutorial, you’re now equipped to implement offline access in your WKWebView-powered apps. Hope this was helpful :)</p><p>Happy coding!</p><p>P.S. If your app uses webviews, you might find the article below interesting too.</p><p><a href="https://medium.com/@bahalek/setting-up-js-bridge-between-your-webpage-and-wkwebview-in-your-ios-app-4ec8ca8230f7">Setting up JS bridge between your webpage and WKWebview in your iOS app</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61daf528df2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/storing-wkwebview-content-for-offline-access-in-your-ios-app-b61daf528df2">Caching WKWebView content for offline access in your iOS app</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Debugging in Xcode: Using Conditional Breakpoints for Efficient Debugging]]></title>
            <link>https://medium.com/@bahalek/mastering-debugging-in-xcode-using-conditional-breakpoints-for-efficient-debugging-2c9ce6235792?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c9ce6235792</guid>
            <category><![CDATA[conditional-breakpoints]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 18:54:53 GMT</pubDate>
            <atom:updated>2023-03-17T18:54:53.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rCtEcVVyhEo16yN1" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, we will cover the use of conditional breakpoints to improve the efficiency of your debugging process.</p><p>But before we begin, let’s quickly go over what a breakpoint is. A breakpoint is a debugging tool that allows you to pause the execution of your code at a specific point to inspect its state. And a conditional breakpoint is a breakpoint that is triggered only when a certain condition is met.</p><p>Now, let’s dive into the fun part — using conditional breakpoints.</p><h4><strong>Step 1: Identify the area of your code that needs a breakpoint.</strong></h4><p>Let’s say we have a function that calculates the number of beers needed for a party. Our function takes two parameters: the number of people attending the party and the number of hours the party will last.</p><pre>func calculateBeer(for people: Int, hours: Int) -&gt; Int {<br>    let beersPerPersonPerHour = 2<br>    let totalBeersNeeded = people * hours * beersPerPersonPerHour<br>    return totalBeersNeeded<br>}</pre><p>Xcode playgrounds do not support breakpoints, so to demonstrate how the breakpoints work, I will put the code in a starter Swift Playground App project available from Xcode -&gt; File -&gt; New -&gt; Project -&gt; Swift Playgrounds App. To invoke the calculateBeer function I will add a button on the ContentView that will run a for-loop when tapped. Run the app and tap the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5s2jReHt3cMUZKr4Jm7Sg.png" /></figure><h4><strong>Step 2: Add a breakpoint.</strong></h4><p>To add a breakpoint, click on the line number where you want to pause the code execution. You will see a blue arrow appear on the left , indicating that a breakpoint has been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rwv-XrgkZRC9uY8OEBbVg.png" /></figure><h4><strong>Step 3: Add a condition.</strong></h4><p>To add a condition, right-click on the breakpoint and select “Edit Breakpoint”. In the condition field, type in a condition that will trigger the breakpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8L6v2f8QLrdpUhvcWAcEJw.png" /></figure><p>For example, let’s say we want to trigger the breakpoint if the number of beers needed is greater than 100. We can add the condition “totalBeersNeeded &gt; 100” and add a message that says “Party too lit! More beer needed!”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxzUhQTL5xQsAIWV6p2Blg.png" /></figure><h4><strong>Step 4: Run the app.</strong></h4><p>Now that our breakpoint is set with a condition, let’s run our app and see it in action. As soon as our condition is met, Xcode will pause the execution of our code and show us the message we added. We can then inspect the state of our code and fix any issues that we find.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lb0qxBWH3MtJsvfQ4k0yAw.png" /></figure><p>And there you have it! A fun and useful way to use conditional Xcode breakpoints.</p><h4><strong>Conclusion</strong></h4><p>Using conditional breakpoints in Xcode can help you optimize your debugging process by allowing you to focus on the specific conditions that are relevant to your current debugging session. By using logical expressions to define your conditions, you can quickly identify the areas of your code that require attention, and improve the overall efficiency of your debugging process.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c9ce6235792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking your iOS app crashes, OOMs and other terminations with MetricKit]]></title>
            <link>https://medium.com/@bahalek/tracking-your-ios-app-crashes-ooms-and-other-terminations-with-metrickit-891e77a6e6d5?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/891e77a6e6d5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[oom]]></category>
            <category><![CDATA[metrickit]]></category>
            <category><![CDATA[crash]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Fri, 21 Oct 2022 02:37:44 GMT</pubDate>
            <atom:updated>2025-03-03T03:19:38.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lsfs_ShinSb9LD20" /><figcaption>Photo by <a href="https://unsplash.com/@lilzidesigns?utm_source=medium&amp;utm_medium=referral">lilzidesigns</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Before MetricKit</h3><p>Tracking your app crashes and other terminations is vital for monitoring your app health. Before MetricKit iOS developers used to rely to 3rd party solutions to track any app crashes and OOMs. Crashlytics and Instabug are two of the most popular ones, but even they did not guarantee accurate OOM data. This is due to the fact that when an OOM happens, your app is killed by the system and there is no time for it to react or try to log the event. That’s why developers used to rely on various heuristics at the app start to determine whether an OOM happened.</p><p>Example checks from this <a href="https://medium.com/compass-true-north/the-case-of-ios-oom-crashes-at-compass-96ec812397e8">article</a> by the team at Compass in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*0gpHfMHZQOiJ0PBi2qcHZA.png" /><figcaption><a href="https://medium.com/compass-true-north/the-case-of-ios-oom-crashes-at-compass-96ec812397e8">https://medium.com/compass-true-north/the-case-of-ios-oom-crashes-at-compass-96ec812397e8</a></figcaption></figure><p>If that’s not enough, here is an <a href="https://developer.apple.com/forums/thread/113742">interesting read</a> on why 3p crash reporters are not a good idea.</p><h3>With MetricKit</h3><p>Apple introduced <a href="https://developer.apple.com/documentation/metrickit">MetricKit</a> in 2019 with iOS 13, but it did not have much to it at the time. With iOS 14 MetricKit received much more functionality. Now you can track diagnostic information about your apps terminations and crashes once every 24 hours at most. With iOS 15 this has been expanded to instantaneous updates.</p><p>All you need to do is get a shared instance of <a href="https://developer.apple.com/documentation/metrickit/mxmetricmanager">MXMetricManager</a>, <a href="https://developer.apple.com/documentation/metrickit/mxmetricmanager/3131901-add">subscribe</a> to its updates and implement <a href="https://developer.apple.com/documentation/metrickit/mxmetricmanagersubscriber">MXMetricManagerSubscriber</a> protocol.</p><p>Once subscribed to MXMetricManager updates, you will start receiving <a href="https://developer.apple.com/documentation/metrickit/mxmetricpayload">MXMetricPayload</a> along with <a href="https://developer.apple.com/documentation/metrickit/mxdiagnosticpayload">MXDiagnosticPayload</a>. MXMetricPayload contains <a href="https://developer.apple.com/documentation/metrickit/mxappexitmetric">applicationExitMetrics</a> that contains <a href="https://developer.apple.com/documentation/metrickit/mxforegroundexitdata">foregroundExitData</a> and <a href="https://developer.apple.com/documentation/metrickit/mxbackgroundexitdata">backgroundExitData</a>. As can be guessed from the names foreground exit data corresponds to the times that the app was terminated while in foreground, either by a crash, OOM, user termination etc.</p><p>For all types of termination types check <a href="https://developer.apple.com/documentation/metrickit/mxforegroundexitdata">Apple documentation</a>.</p><h3>Getting number of OOMs for your app</h3><p>For this example I will just extract the number of OOMs from <a href="https://developer.apple.com/documentation/metrickit/mxmetricpayload">MXMetricPayload</a> and track them in a custom MetricManager class.</p><ol><li>In AppDelegate.swift add import MetricKit</li><li>In AppDelegate.swift’s <a href="https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622921-application">didFinishLaunchingWithOptions</a>: add your metricManager as a subscriber to <a href="https://developer.apple.com/documentation/metrickit/mxmetricmanager">MXMetricManager</a>.</li></ol><pre>//metricManager is instance of your custom MetricManager class<br>//you might want to use your dependency injection solutions to<br>//initialize it</pre><pre>MXMetricManager.shared.add(metricManager)</pre><p>3. Inside your MetricManager class implement methods for <a href="https://developer.apple.com/documentation/metrickit/mxmetricmanagersubscriber">MXMetricManagerSubscriber</a> protocol.</p><pre>extension MetricManager: MXMetricManagerSubscriber {<br>  func didReceive(_ payloads: [MXMetricPayload]) {<br>    // these payloads contains information on your app exits<br>    // both foreground and background<br>    <strong>for</strong> payload <strong>in</strong> payloads {<br>        <strong>if</strong> <strong>let</strong> appExitMetrics = payload.applicationExitMetrics {<br>            <strong>let</strong> oomCount = appExitMetrics.foregroundExitData<br>                           .cumulativeMemoryResourceLimitExitCount</pre><pre>            //TODO: track this OOM count based on your needs<br>        }<br>    }<br>  }<br><br>  func didReceive(_ payloads: [MXDiagnosticPayload]) {<br>    // this payload contains information for your crashes <br>    // along with crashlogs<br>  }<br>}</pre><h3>Conclusion</h3><p>In this example we only got the foreground OOM count, MetricKit has a lot more data that can help you monitor your app’s health and keep your users happy :)</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=891e77a6e6d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending Data Between watchOS and iOS App Using Watch Connectivity]]></title>
            <link>https://medium.com/better-programming/sending-data-between-watchos-and-ios-apps-cf924e21b3c2?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf924e21b3c2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 22:00:27 GMT</pubDate>
            <atom:updated>2025-03-03T03:18:32.870Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setup a communication bridge between SwiftUI iOS and watchOS apps for status updates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMlEPrZI6VLtOOyXjJditQ.png" /><figcaption>Source: <a href="https://undraw.co/">undraw</a></figcaption></figure><p>This is a continuation to <a href="https://betterprogramming.pub/adding-a-watch-app-to-your-existing-ios-application-xcode-13-d229dd9422c5">previous article</a> that showed how to add a watchOS app target to an existing iOS project. This part covers:</p><ul><li><a href="https://developer.apple.com/documentation/watchconnectivity">Watch Connectivity</a> and methods it provides for data transfer between iOS and watchOS apps.</li><li>Configuring and activating WCSession to implement two-way communication between iOS and watchOS apps.</li><li>Sending messages.</li><li>Receiving messages.</li></ul><p>As before I am using Xcode13.2 for this demo.</p><h3>Watch Connectivity</h3><p>To transfer data between the iOS app and the watch app, we need to use <a href="https://developer.apple.com/documentation/watchconnectivity/wcsession">WCSession</a>:</p><blockquote>The object that initiates communication between a WatchKit extension and its companion iOS app.</blockquote><p>WCSession provided five ways to transfer data — and can be used to send data from the iOS app to the watch app and vice versa.</p><ul><li><a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615621-updateapplicationcontext">updateApplicationContext(_:)</a> can be used to send data to the counter app when the counter app only cares about the latest state of that data (example: number of steps done during the day, the user will only care about the latest value). This method will overwrite the previous data, so only the latest update will be available.</li><li><a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615687-sendmessage">sendMessage(_:replyHandler:errorHandler:)</a> can be used when you need to transfer a dictionary of data immediately. Apple does not guarantee the delivery of these messages. For the messages to be delivered, the counterpart must be reachable. While the iOS app will wake from the background and become reachable if the watch is used to send the data, the opposite is not true for the watch app.</li><li><a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615617-sendmessagedata">sendMessageData(_:replyHandler:errorHandler:)</a> same as above, but for sending a Data object instead of a dictionary.</li><li><a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615671-transferuserinfo">transferUserInfo(_:)</a> is used to transfer a dictionary of data in the background. These messages are guaranteed to be delivered in FIFO manner as soon as possible, even if the counter app is suspended.</li><li><a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615667-transferfile">transferFile(_:metadata:)</a> is used to transfer files like images and optional dictionaries with file metadata.</li></ul><h3>Setting up WCSession</h3><p>You can add code to configure and activate a WCSession instance directly inside of the classes from where you will be sending or receiving the data, but that would require every class to conform to the WCSessionDelegate protocol. So instead we will do that in a singleton class.</p><p>Create a folder in your Xcode project and add a new swift file that can be used by both iOS app target and watch app extension target.</p><p>I called the file WatchConnectivityManager and added the usual singleton code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Umq8tZxs6grpyD_5NQm5ZQ.png" /></figure><p>To configure and activate a session, you need to get a reference to the default session object, assign a delegate to it and call activate().</p><p>This will establish a connection between iOS and watchOS apps:</p><pre>if WCSession.isSupported() {<br>    WCSession.default.delegate = self    <br>    WCSession.default.activate()<br>}</pre><p>So we will add this code to our WatchConnectivityManager’s constructor and add conformance to <a href="https://developer.apple.com/documentation/watchconnectivity/wcsessiondelegate">WCSessionDelegate</a> protocol. <a href="https://developer.apple.com/documentation/watchconnectivity/wcsessiondelegate">WCSessionDelegate</a> protocol inherits from <a href="https://developer.apple.com/documentation/objectivec/nsobjectprotocol">NSObjectProtocol</a> , which means WatchConnectivityManager will need to inherit from NSObject.</p><p>One more point to take into account is that delegate methods sessionDidBecomeInactive and sessionDidDeactivate are not available on watchOS so we will need to add a compiler check for the platform <em>(line 22)</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62aa712156a855ddedb2326c3c39208/href">https://medium.com/media/e62aa712156a855ddedb2326c3c39208/href</a></iframe><p>Line 25 activates a session in case it gets deactivated. This can happen if the user owns several watches and we need to support watch switching.</p><p>At this point, you have established a connection between the watch app and the iOS app. We will look at sending and receiving messages next.</p><h3>Sending Messages</h3><p>For the purpose of this demo, we will just send a simple string from the watch to the iOS app and vice versa whenever the user taps on a “Hello World” button.</p><p>transferUserInfo(:_) method suits the most for our use case, but according to <a href="https://developer.apple.com/documentation/watchconnectivity/wcsessiondelegate/1615633-session">Apple documentation</a> the system will not call the didReceiveUserInfo delegate method on simulator.</p><p>So we would not be able to respond to receiving these messages on a simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu_1gVtgGSSJWz-CqjIbng.png" /></figure><p>Thus I will use <a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615687-sendmessage">sendMessage(_:replyHandler:errorHandler:)</a> instead.</p><p>First of all, let’s add the function in WatchConnectivityManager to send a simple text message to the watch if sent from the iOS app and vice versa. Don’t forget to check that you have an active session and a paired device.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a36898f5697f722df0e140fb33fd2e/href">https://medium.com/media/e0a36898f5697f722df0e140fb33fd2e/href</a></iframe><p>Now add a button in content view to call this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/996fc73a3c9fbff5c54873071e1dc7a5/href">https://medium.com/media/996fc73a3c9fbff5c54873071e1dc7a5/href</a></iframe><p>Now let’s write the code to receive the message and test that it works.</p><h3>Receiving messages</h3><p>To receive the messages sent using <a href="https://developer.apple.com/documentation/watchconnectivity/wcsession/1615687-sendmessage">sendMessage(_:replyHandler:errorHandler:)</a> method we need to implement the session(_:didReceiveMessage:) method from WCSessionDelegate protocol.</p><p>Once we receive the message we can store it as a published variable in WatchConnectivityManager on the main thread since we should always make sure we publish on the main thread.</p><p>Our content view will then observe the changes to this variable and display a pop-up alert when the state changes.</p><p>Final code in WatchConnectivityManager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0b30f9e65feae15884e13eb49b211df/href">https://medium.com/media/e0b30f9e65feae15884e13eb49b211df/href</a></iframe><p>Now let’s add code to observe changes to the notification message in our content view. In the content view, we will add ObservedObject variable for the WatchConnectivityManager.</p><pre>@ObservedObject <strong>private</strong> <strong>var</strong> connectivityManager = WatchConnectivityManager.shared</pre><p>And then we will bind the notificationMessage from watchConnectivityManager to the alert.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36559ebc63f6213f7ee7355b552c1c42/href">https://medium.com/media/36559ebc63f6213f7ee7355b552c1c42/href</a></iframe><p>Now when you run the app on your phone and the watch and tap on “Hello World!” button, you will see the alert on the counter app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uap_ASOoQdDweTBjrYfBmQ.png" /></figure><p>Now you have an app that runs both on the watch and on the phone and can send data back and forth between your phone and watch to update the UI and show notifications. Hope this was helpful.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf924e21b3c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/sending-data-between-watchos-and-ios-apps-cf924e21b3c2">Sending Data Between watchOS and iOS App Using Watch Connectivity</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a SwiftUI watchOS Weather App for an Existing iOS Application]]></title>
            <link>https://medium.com/better-programming/adding-a-watch-app-to-your-existing-ios-application-xcode-13-d229dd9422c5?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/d229dd9422c5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 20:09:19 GMT</pubDate>
            <atom:updated>2025-03-03T03:20:16.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>Add a watchOS target to your existing iOS project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e0pZGBM7lVdHa6T1" /><figcaption>Photo by <a href="https://unsplash.com/@raagesh?utm_source=medium&amp;utm_medium=referral">Raagesh C</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This demo will continue building upon the app created in the previous <a href="https://betterprogramming.pub/simple-weather-app-with-swiftui-ac41200a9d4d">article</a>.</p><p>In this part we will:</p><ul><li>Create a new watchOS target inside of our existing iOS project.</li><li>Run the existing app on your watch</li><li>Launch and run the app on Xcode using iPhone and Watch simulators</li></ul><p>As before I am using Xcode13.2 for this demo.</p><h3>Add a watchOS target to existing iOS project</h3><p>We will start where we left off in <a href="https://medium.com/@bahalek/simple-weather-app-with-swiftui-ac41200a9d4d">part 1</a>. So open your project in Xcode.</p><p>To add a WatchOS target to your project:</p><ol><li>Choose File -&gt; New -&gt; Target</li><li>From the templates window, choose “Watch App for iOS App” from the WatchOS tab and click Next.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ko1hS3sXSnNyN-4nmSax9g.png" /></figure><p>3. Choose a product name and click “Finish”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUUn7GESz_cmrEiXk54aGQ.png" /></figure><p>4. In the next pop-up that asks if you want to activate the scheme for WatchApp complication feel free to choose “Cancel” as we won’t be using it in this tutorial.</p><p>After these steps, you should end up with the following project structure and new files added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVtxxx-wZVJmJBXaKMbdmg.png" /></figure><h3>Running your app on the watch</h3><p>Delete the WeatherAppApp.swift and ContentView.swift files from the Watch App target, since we will be reusing the ones from the iOS app.</p><p>To be able to share the files between both targets, select WeatherAppApp.swift, ContentView.swift, WeatherModel.swift, WeatherAPIClient.swift and from the File Inspector Tab add them to the WeatherWatchApp WatchKit Extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEGQp_CMY8ER-QL6YE1Bmw.png" /></figure><p>If you run the newly created WeatherWatchApp scheme you will see that Xcode will automatically attach a phone simulator to your watch simulator.</p><p>If you want to attach the watch to a specific simulator, you can do so from “Window -&gt; Devices and Simulators”.</p><p>Choose a simulator of your choice and tap on the + icon on the paired watches pane to add a watch simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPy9z-VeJXx5DJNcTmNh7A.png" /></figure><p>If you don’t want to always launch a phone simulator when you run the watch app, select your watch app extension target, and in General settings choose “Supports Running Without iOS App Installation”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1OOniDqG4StUfN66Foz7w.png" /></figure><p>If you run the WeatherWatchApp scheme now, you will see it launch only on the watch simulator, without installing the app on the phone simulator.</p><p>However, you will see that you will land on the default screen <em>(middle image below)</em> since location permissions have not been enabled for the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oOV_zDq73wX99tMnYCBjA.png" /></figure><p>To enable location permissions for the watch app, add the same location tracking permission as you did for the iOS app target to your watch app extension target as shown below and the next time you run your app you should see the app ask you to enable location services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5yfq6oXmvXjZuibBE--Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGorS0zXRC2VKdelhbvDGg.png" /></figure><p>To make sure the UI fits on the watch, update the ContentView.swift file to wrap the main VStack inside of a ScrollView as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJ8E-_ev9AurP2TJe1gDrg.png" /></figure><h3>Conclusion</h3><p>Now you have an app that runs both on the Apple watch and on the iPhone.</p><p>In the <a href="https://medium.com/@bahalek/sending-data-between-watchos-and-ios-apps-cf924e21b3c2">next part</a> I will go over establishing watch connectivity to send data back and forth between your iPhone and watch to update the UI and show notifications.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d229dd9422c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/adding-a-watch-app-to-your-existing-ios-application-xcode-13-d229dd9422c5">Build a SwiftUI watchOS Weather App for an Existing iOS Application</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an iOS Weather SwiftUI App]]></title>
            <link>https://medium.com/better-programming/simple-weather-app-with-swiftui-ac41200a9d4d?source=rss-3a9c66959e30------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac41200a9d4d</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Baha Abisheva]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 01:41:37 GMT</pubDate>
            <atom:updated>2025-03-03T03:20:32.508Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leverage the tomorrow.io API to display the weather for the day</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHqmqssYJbcutHHPd7CcKA.png" /><figcaption>Source: <a href="https://undraw.co/">undraw</a></figcaption></figure><p>For a recent hackathon at our company, our team decided to add a watch app to our existing iOS application.</p><p>My part in it was to integrate a third-party weather API for user suggestions based on the weather for the day and display daily notifications on both the phone and the watch. We did not win the hackathon but this article was born out of it.</p><p>This tutorial is divided into three parts. Links to the next part is at the end.</p><p>In the first part, I will walk through integrating the weather API with a new iOS app. In the second part, I will walk through adding a Watch App to an existing iOS application. Third part will talk about Watch Connectivity and sending data between watchOS app and iOS app.</p><p>I will be using Xcode13.2 and SwiftUI.</p><h3>Choosing Third-party Weather API</h3><p>The first step is to find the API that works for you. I used <a href="https://rapidapi.com/blog/access-global-weather-data-with-these-weather-apis/">this article</a> to help me get started. From this article, I chose to look at the following three options until I stopped at tomorrow.io.</p><ul><li><a href="https://openweathermap.org/appid">OpenWeatherMap</a> has a very simple API, good documentation and it’s easy to onboard too. You just need to generate the API key for yourself and you are good to go. However, at the time of writing, this API did not support HTTPS requests and that was a no for our app.</li><li><a href="https://darksky.net/dev">DarkSky</a> also had a very simple API to use. However unfortunately at the time of writing, they were already not accepting any new signups. <a href="https://blog.darksky.net/dark-sky-has-a-new-home/">They joined Apple</a> and would stop supporting their API by the end of 2021.</li><li><a href="https://app.tomorrow.io/home">tomorrow.io</a> has great functionality, documentation, and customer support. They also support HTTPS. It was a bit of an overkill for our app since the response was a nested json that would require several structs to parse using Swift’s Codable protocol, but if we wanted to expand functionality of the app, it would come in very handy. They have multiple subscription options and the free version is enough for a personal side project/hackathon. You get 500 calls per day, 1 user and 1 location.</li></ul><p>So I will be using tomorrow.io for this tutorial.</p><h3>Creating a new Xcode project</h3><p>I will not go into details for this step. <a href="https://developer.apple.com/documentation/xcode/creating-an-xcode-project-for-an-app">Here</a> is Apple’s documentation on how to create a new Xcode project if you need it.</p><p>Choose the iOS App template, call it “WeatherApp” and choose SwiftUI for the interface. Select a folder where to store the project and Xcode should generate all of the necessary files to start writing our app. Here is what your project structure should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0t9c2NLvmVD5dlUweG6oSQ.png" /></figure><h3>Creating Dummy UI</h3><p>Let’s first make a dummy UI with hardcoded weather values, we will later on update the values based on the results we get from calling tomorrow.io. Replace the body of your ContentView with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bddaa2cdc850bc93a1a5895867e8eca/href">https://medium.com/media/7bddaa2cdc850bc93a1a5895867e8eca/href</a></iframe><p>This will create a vertical layout on which we will have two main parts.</p><p>The top part will contain icon for the current weather<em> (line 4)</em> with the temperature text <em>(line 6)</em> right next to it.</p><p>Below that, we will have a suggestion text <em>(line 9)</em> that will change depending on the weather.</p><p>For the weather icon, I am using <a href="https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/">SF Symbols</a> that Apple provides for use in your app. You can view all of the available symbols using <a href="https://developer.apple.com/sf-symbols/">this app</a>.</p><p>You should end up with the following UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTZS4hAzRyDHFoMlV-_zow.png" /></figure><p>We will be reusing the same view for the Watch App, so let’s leave it simple as it is right now.</p><h3>Integrate Tomorrow.io</h3><p>Sign up with tomorrow.io and go to your <a href="https://app.tomorrow.io/development/keys">development dashboard</a> to get your access key and try out a sample API call. This is what your dashboard should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5maMLATlE0r3ahUjf_6hg.png" /></figure><p>Browse through their <a href="https://docs.tomorrow.io/reference/key-concepts">documentation</a> to get a sense of what other information you can get using tomorrow.io API.</p><p>For this demo app you will use the <a href="https://docs.tomorrow.io/reference/get-timelines">timelines API</a> and you only need the temperature and weatherCode fields for the current hour in the response.</p><p>You can find all other available data <a href="https://docs.tomorrow.io/reference/data-layers-overview">here</a>. To modify your request to include weatherCode field and limit to only 1 value for the current hour. Replace {$YOUR_KEY} with your access key instead. The final request should be:</p><pre><a href="https://api.tomorrow.io/v4/timelines?location=40.7579787,-73.9877313&amp;fields=temperature&amp;fields=weatherCode&amp;units=metric&amp;timesteps=1h&amp;startTime=2021-12-25T19:36:11Z&amp;endTime=2021-12-25T20:36:11Z&amp;apikey=2IG0jVndUp4wNRP2kEJUGb5chDLWPWsZ">https://api.tomorrow.io/v4/timelines?location=40.7579787,-73.9877313&amp;fields=temperature&amp;fields=weatherCode&amp;units=metric&amp;timesteps=1h&amp;startTime=2021-12-25T19:36:11Z&amp;endTime=2021-12-25T20:36:11Z&amp;apikey=</a>{$YOUR_KEY}</pre><p>Try it out in your browser. The response will be a JSON in the following format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*mUkZbyfD32n3gH-6kxGjHA.png" /></figure><p>Now you are ready to integrate the API with your app.</p><h3>Adding API Client and Response Models to your App</h3><p>Since we only need to make one type of request and writing a scalable API client is not the purpose of this demo, our API Client will be very simple.</p><p>For a tutorial on how to write a more complex and scalable API client follow this <a href="https://medium.com/makingtuenti/writing-a-scalable-api-client-in-swift-4-b3c6f7f3f3fb">link</a>, it’s a bit outdated but the concepts and architecture should still be relevant. And here is <a href="https://medium.com/macoclock/swift-generic-api-854afdb9315e">another good one</a> that is more recent and uses Combine.</p><p>For our purposes create a folder WeatherAPIClient to store all files related to the business logic related to the request to our weather API.</p><p>First, let’s create the models for the response. We will use Codable protocol for <a href="https://www.avanderlee.com/swift/json-parsing-decoding/">JSON parsing</a>.</p><p>From the JSON above, we will need to retrieve temperature and weatherCode fields. The rest can be discarded.</p><p>Create a new Swift file inside of your new folder and call it WeatherModel.swift. Populate it with the following models:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/894458efac594d3fb06a97865c79502b/href">https://medium.com/media/894458efac594d3fb06a97865c79502b/href</a></iframe><p>Next, we can create the API client itself that will return WeatherValue on successful request completion.</p><p>In the same folder create a new file WeatherAPIClient.swift. Populate it the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95613527d126f4e0f9effd080285a15f/href">https://medium.com/media/95613527d126f4e0f9effd080285a15f/href</a></iframe><p>To make the API call we need the user’s current location and startTime of now formatted with ISO8601 format as per the API documentation.</p><p>So we need a location manager and a date formatter object in our class. We request user location upon initialization. Later on, every time the user location is updated we request the weather update.</p><p>As per Apple documentation, you will need to add the correct keys into your info.plist file:</p><blockquote>To prepare your app for calling <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620562-requestwheninuseauthorization">requestWhenInUseAuthorization()</a> or <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620551-requestalwaysauthorization">requestAlwaysAuthorization()</a>, you must add keys with purpose strings to your app&#39;s Info.plist file. The system displays your purpose strings in the authorization request dialogs.</blockquote><p>A SwiftUI project generated using Xcode 13 does not get separate info.plist file. Instead, you can use the Info tab of your target’s settings as shown below.</p><p>For our app we only need the location while the app is in use, so add the NSLocationWhenInUseUsageDescription key and add a description string as to why you need the user location.</p><p>This text will show up when the location authorization permission dialog is shown to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1enHfvTi_O6zNMwiT-FTSg.png" /></figure><p>To make the API request we are using URLSession and <a href="https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html">async/await</a> to make the syntax more clear, with fewer closures.</p><p>async stands for asynchronous and is used to define that the function is performing asynchronous work. await is used to call an async function to mark the execution suspension point. Once the async function is matched with await returns, we continue execution from that point.</p><p>I left out handling the errors for now. You can decide to present the errors to the user in a pop-up or do any other processing of the errors that you need.</p><h3>Connecting the Model to UI</h3><p>Now we need to connect the result of the API request with our UI.</p><p>First of all, we need to translate the weatherCode that we receive from tomorrow.io into our custom enum that will have an image and a text description.</p><p>Add the following to your WeatherModel.swift:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb0fa7a0f2f7b7407f20df86526e7dbf/href">https://medium.com/media/fb0fa7a0f2f7b7407f20df86526e7dbf/href</a></iframe><p>Add a model that will be used inside of the ContentView. Add Weather struct to the WeatherModel.swift.</p><p>It needs to conform to Identifiable protocol so that we can set it up as a published variable in the API client and update the UI every time data changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1de4336ee99cf73276ff0781deeefb6a/href">https://medium.com/media/1de4336ee99cf73276ff0781deeefb6a/href</a></iframe><p>Now update the WeatherAPIClient class to conform to ObservableObject protocol and publish the changes to the weather variable.</p><p>Also, update currentWeather variable in WeatherAPIClient class to a @Published property wrapper:</p><pre>@Published <strong>var</strong> currentWeather: Weather?</pre><p>Then you need to update how we handle the response to our API call.</p><p>We need to make sure we create the new Weather struct from the response.</p><p>Since now it’s a published variable, we need to do it on the main queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e869a32fb876b6ba31a24be954a11dd/href">https://medium.com/media/2e869a32fb876b6ba31a24be954a11dd/href</a></iframe><p>Finally WeatherAPIClient.swift should look as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79d75c5d3a729271d68345ac49892bf4/href">https://medium.com/media/79d75c5d3a729271d68345ac49892bf4/href</a></iframe><p>At last, we need to update our ContentView to observe the published variable and show a default view with a Refresh button if the weather info is not available.</p><p>Your final ContentView.swift code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adebc5a5ef4f6d43fd8593a38d10568d/href">https://medium.com/media/adebc5a5ef4f6d43fd8593a38d10568d/href</a></iframe><p>The output of the iOS SwiftUI app in action is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsIiJnKkcnomOIa85jRqJg.png" /></figure><p>Now you are ready to run the app. The final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*zzP70xf3SRACq5fsSiiFQA.gif" /></figure><h3>Conclusion</h3><p>Now you have a SwiftUI project that is integrated with tomorrow.io to fetch current weather for the current location.</p><p>The next step will be creating a companion Watch App for this app. You can do that in the <a href="https://medium.com/@bahalek/adding-a-watch-app-to-your-existing-ios-application-xcode-13-d229dd9422c5">next tutorial</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac41200a9d4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/simple-weather-app-with-swiftui-ac41200a9d4d">Build an iOS Weather SwiftUI App</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>