<?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 Fer Cervantes Alvarez on Medium]]></title>
        <description><![CDATA[Stories by Fer Cervantes Alvarez on Medium]]></description>
        <link>https://medium.com/@fernando.cervantes_89089?source=rss-81e95376e1f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a6jQ5fzJftDwMAGuam4szA.jpeg</url>
            <title>Stories by Fer Cervantes Alvarez on Medium</title>
            <link>https://medium.com/@fernando.cervantes_89089?source=rss-81e95376e1f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:50:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fernando.cervantes_89089/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[Making a WatchOS app with SwiftUI from scratch, with data fetching]]></title>
            <link>https://medium.com/macoclock/making-a-watchos-app-with-swiftui-from-scratch-with-data-fetching-68981acf615f?source=rss-81e95376e1f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/68981acf615f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple-watch]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Fer Cervantes Alvarez]]></dc:creator>
            <pubDate>Wed, 06 May 2020 02:50:39 GMT</pubDate>
            <atom:updated>2020-05-13T22:09:43.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SNuJZlw8IJN06Tbf" /><figcaption>Image by Fabian Albert, <a href="https://unsplash.com/photos/bl_NUhqLC8o">https://unsplash.com/photos/bl_NUhqLC8o</a></figcaption></figure><p>Hi everyone!</p><p>In this post, I’ll guide you step by step on creating a WatchOS app using SwiftUI and a couple of libraries to handle network requests and JSON responses. In 35 minutes, we will have a beautiful and functional, independent app for your Apple Watch.</p><p>Prerequisites</p><ul><li>Xcode 11 (You can download it from the Mac App Store)</li><li>Cocoapods (https://guides.cocoapods.org/using/getting-started.html)</li><li>An API key for using NewsAPI.org (Get yours for free from <a href="https://newsapi.org/)">https://newsapi.org/)</a></li><li>Visual Studio Code or some text editor if you’re unfamiliar with terminal-based code editors.</li></ul><p>For previewing your App</p><ul><li>iPhone</li><li>Apple Watch</li><li>Lightning cable to connect your iPhone to your Mac</li></ul><p>We will create an app that fetches data from NewsAPI (https://newsapi.org/) and displays the different articles we fetch in a list, so we can tap and read some bits of news on the go.</p><p>We’ll be using the AlamoFire library (https://github.com/Alamofire/Alamofire) for making network requests quickly, as well as SwiftyJSON (https://github.com/SwiftyJSON/SwiftyJSON) to handle the response easily and turn it into usable elements on our UI, and KingFisher (https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) to download and cache images easily on to our App.</p><p>So, if you have all the prerequisites ready, let’s begin!</p><p>To start, open Xcode and tap on Create a new Xcode project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCgbUqEgdF2kseX8ESMY5w.png" /></figure><p>On the WatchOS tab, select Watch App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6H0Sp-LN2tCzSEzlynF87g.png" /></figure><p>I’ll name my App WristNews, but feel free to call it however you want! Make sure you have Swift as Language and SwiftUI as User Interface and save it in an easy to access directory since we’ll access to it later via the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Ne8F5Wk2WdFgRN2wA0geMg.png" /></figure><p>Now that we created our App, let’s jump to code!</p><p>On the right side, tap on the Resume button to quickly build your App and trigger the preview on the canvas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUM5snpOVF_hD6hDH62elw.png" /></figure><p>Now, you have the code on the left side and the preview on the right side. We will edit code and rebuild the preview so we can see our App come to life with each step.</p><p>Replace the “Hello, World” text on the text element by “WristNews” and add the <strong>.font(.title)</strong> and <strong>.fontWeight(.thin)</strong> modifiers at the end.</p><pre>import SwiftUI</pre><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;WristNews&quot;)<br><strong>            .font(.title)<br>            .fontWeight(.thin)</strong><br>    }<br>}</pre><pre>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><p>Notice how the preview updates as you change the code. You can also tap on each element in the preview to get a visual interface to make changes to your UI. This interface to the right side is called The Inspector.</p><p>Wrap your Text element in a VStack. A VStack is a container that stacks elements vertically. It is useful for keeping consistency and order in your UI. It also will let you apply alignment and padding properties to the whole container instead of trying to accommodate each element on the screen manually.</p><pre>import SwiftUI</pre><pre>struct ContentView: View {<br>    var body: some View {<br><strong>        VStack{</strong><br>            Text(&quot;WristNews&quot;)<br>                .font(.title)<br>                .fontWeight(.thin)<br>        <strong>}</strong><br>    }<br>}</pre><pre>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><p>After having done this, let’s add some more elements to our View.</p><p>Let’s add another Text element below the one we already have.</p><pre>import SwiftUI</pre><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack{<br>            Text(&quot;WristNews&quot;)<br>                .font(.title)<br>                .fontWeight(.thin)<br>            <br><strong>            Text(&quot;Daily news, delivered on your wrist.&quot;)<br>                .fontWeight(.thin)<br></strong>        }<br>    }<br>}</pre><pre>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><p>Now, we’re going to use the inspector to make a change in our UI.</p><p>Tap on any place of the word <strong>VStack</strong>, and notice how a blue box appears around the Text elements on your preview, as well as the inspector populating with different options. Now, tap on the second to last button on the alignment options to align the content on our VStack to the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qBACXPhbLG6c4tRdbGQ0Q.png" /></figure><p>Then, on your preview, tap the second Text we added, and apply a left alignment to it as well, so our preview ends up looking like this:</p><p>Now, we’re going to create another view that takes us to the List of articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*OHyR_kN35kPB8usv3_69mg.png" /><figcaption>Lookin’ good!</figcaption></figure><p>Press CMD+N to create a new file, and select SwiftUI View from the List of options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEM1lc-zwx3gFyXUpZ5dKQ.png" /></figure><p>Let’s save the View with the name ArticlesView, and make sure that it’s saved on the WristNews WatchKit Extension Group, as well as the same Target checked. It must look like on the image below, except with ArticlesView instead of SwiftUIView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Fok5y7LTt1-PL4QWzjM5sQ.png" /><figcaption>I took the screenshot before changing the file name, sorry!</figcaption></figure><p>Replace the “Hello World” text with “Articles” and wrap it in a VStack. We may remove it later, but let’s leave it like that for now. We’ll come back to this file later.</p><pre>import SwiftUI</pre><pre>struct ArticlesView: View {<br>    var body: some View {<br>        <strong>VStack{<br>            Text(&quot;Articles&quot;)<br>        }</strong><br>    }<br>}</pre><pre>struct ArticlesView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ArticlesView()<br>    }<br>}</pre><p>Now, before we start adding articles, we first need to define what an article is, and what will it contain, in order to tell the UI what to display.</p><p>This is a sample of the data we’re going to get from NewsAPI, so we’ll base on this sample to define the Article object.</p><pre>{<br> &quot;status&quot;: &quot;ok&quot;,<br> &quot;totalResults&quot;: 38,<br> &quot;articles&quot;: [<br>  {<br>   &quot;source&quot;: {<br>    &quot;id&quot;: null,<br>    &quot;name&quot;: &quot;Vogue.com&quot;<br>   },<br>   &quot;author&quot;: &quot;Estelle Tang&quot;,<br>   &quot;title&quot;: &quot;Rosalía Shares Her All-Time Favorite Songs in a Met Gala–Themed Playlist - Vogue&quot;,<br>   &quot;description&quot;: &quot;\&quot;This playlist is a celebratory playlist for the Met, with nods to my all-time favorite songs,     sounds, artists, and references. It has not been possible to celebrate the Met as God intended, but we can     celebrate it in our own way from home.\&quot;&quot;,<br>   &quot;url&quot;: &quot;<a href="https://www.vogue.com/article/rosalia-met-gala-about-time-playlist">https://www.vogue.com/article/rosalia-met-gala-about-time-playlist</a>&quot;,<br>   &quot;urlToImage&quot;: &quot;<a href="https://assets.vogue.com/photos/5eb0a75cd5f359c964b7e0e4/16:9/w_1280,c_limit/">https://assets.vogue.com/photos/5eb0a75cd5f359c964b7e0e4/16:9/w_1280,c_limit/</a>    GettyImages-1162355675.jpg&quot;,<br>   &quot;publishedAt&quot;: &quot;2020-05-05T00:20:29Z&quot;,<br>   &quot;content&quot;: &quot;To commemorate a very different first Monday in May this year, Vogue asked some of our favorite stars to create a playlist featuring timeless songs inspired by the theme of this year&#39;s Met gala and the upcoming Costume Institute exhibition, About Time: Fashio… [+2158 chars]&quot;<br>  },<br> ]<br>}</pre><p>Create a new file, but this time, select Swift File from the List (it should already be selected) and name it Article.</p><p>On this file, we’ll start by defining the Article struct like this:</p><pre>import Foundation</pre><pre>struct Article: Hashable, Identifiable {<br> public var id: String<br> public var title: String<br> public var description: String<br> public var author: String<br> public var link: String<br> public var imageLink: String<br> public var publishedAt: String<br> public var content: String<br>}</pre><p>Each Article will contain:</p><ul><li>A unique identifier</li><li>A Title</li><li>A short description or headline</li><li>The author’s name</li><li>A link to the article on its source</li><li>A link to the headline image</li><li>Time and date of publication</li><li>A short snippet of the content (unless you paid for the NewsAPI service)</li></ul><p>If you paid for the NewsAPI service, you would be able to get the full article content here.</p><p>Now, we’re going to add the initializer method, which will let us create Article objects and represent them visually.</p><pre>import Foundation</pre><pre>struct Article: Hashable, Identifiable {<br> public var id: String<br> public var title: String<br> public var description: String<br> public var author: String<br> public var link: String<br> public var imageLink: String<br> public var publishedAt: String<br> public var content: String<br> <br> <strong>init(title: String, description: String, author: String, link: String, imageLink: String, publishedAt: String, content:String){<br>  self.id = UUID().uuidString<br>  self.title = title<br>  self.description = description<br>  self.author = author<br>  self.link = link<br>  self.imageLink = imageLink<br>  self.publishedAt = publishedAt<br>  self.content = content<br> }</strong><br>}</pre><p>The initializer method takes everything that an Article requires and transforms it into a usable object.</p><p>On this moment, we will proceed to install the libraries we will require for our App, so save and close Xcode, and open your terminal</p><p>cd into the folder of your App, and on the root folder (where your .xcodeproj file is), run the following command</p><pre>pod init</pre><p>This will create a new file called Podfile in your root folder. Now open that file with your preferred text editor, and add the following lines under</p><pre># Pods for WristNews WatchKit Extension</pre><p>And add a # before all the use_frameworks! statements. It should look like this:</p><pre># Uncomment the next line to define a global platform for your project<br># platform :ios, &#39;9.0&#39;</pre><pre>target &#39;WristNews&#39; do<br>  # Comment the next line if you don&#39;t want to use dynamic frameworks<br><strong>  #use_frameworks!</strong></pre><pre># Pods for WristNews</pre><pre>end</pre><pre>target &#39;WristNews WatchKit App&#39; do<br>  # Comment the next line if you don&#39;t want to use dynamic frameworks<br><strong>  #use_frameworks!</strong></pre><pre># Pods for WristNews WatchKit App</pre><pre>end</pre><pre>target &#39;WristNews WatchKit Extension&#39; do<br>  # Comment the next line if you don&#39;t want to use dynamic frameworks<br><strong>  #use_frameworks!</strong></pre><pre># Pods for WristNews WatchKit Extension<br><strong>  pod ‘Kingfisher/SwiftUI’, ‘~&gt; 5.0’<br>  pod &#39;Alamofire&#39;, &#39;~&gt; 5.1&#39;<br>  pod &#39;SwiftyJSON&#39;, &#39;~&gt; 4.0&#39;</strong><br>end</pre><p>You should grab those three lines from their respective webpages (links on the top), since they may have changed by the time you check this tutorial.</p><p>Save and close the file, and on the terminal, enter:</p><pre>pod install</pre><p>And wait for it to finish. After that, to open this folder in Finder, enter:</p><pre>open .</pre><p>You will notice we now have a new file that ends in .xcworkspace, and we will continue with that file from now on.</p><p>Before you open it, make sure <strong>all</strong> instances of Xcode are <strong>closed</strong>. You can now close the terminal.</p><p>On the project navigator, you will find your working files under WristNews &gt; WristNews WatchKit Extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*jVJ24cVIwpFNAKXBiFWJPg.png" /><figcaption>New file structure</figcaption></figure><p>Now, we’re going to create a UI element that represents an Article.</p><p>Create a new file, select SwiftUI View from the List, and name it ArticleRow.</p><p>Since we’re going to use the KingFisher library here to fetch our image, let’s import it at the top with the statement:</p><pre>import struct Kingfisher.KFImage</pre><p>Add a variable called article of type Article on to our View. This tells SwiftUI that this View requires an Article object to work.</p><pre>struct ArticleRow: View {<br><strong>    var article: Article</strong><br>    <br>    var body: some View {<br>        Text(&quot;Hello, World!&quot;)<br>    }<br>}</pre><p>This, of course, will trigger an error on the preview struct below, since we have to provide an Article to the View to work with.</p><p>You can remove the ArticleRow_Previews struct and replace it by copying and pasting this one, since its too much to type by hand:</p><pre>struct ArticleRow_Previews: PreviewProvider {<br> static var previews: some View {<br>  ArticleRow(article: Article(<br>   title: &quot;Rosalía Shares Her All-Time Favorite Songs in a Met Gala–Themed Playlist - Vogue&quot;,<br>   description: &quot;This playlist is a celebratory playlist for the Met, with nods to my all-time favorite songs, sounds, artists, and references. It has not been possible to celebrate the Met as God intended, but we can celebrate it in our own way from home.&quot;,<br>   author: &quot;Estelle Tang&quot;,<br>   link:&quot;<a href="https://www.vogue.com/article/rosalia-met-gala-about-time-playlist">https://www.vogue.com/article/rosalia-met-gala-about-time-playlist</a>&quot;,<br>   imageLink: &quot;<a href="https://assets.vogue.com/photos/5eb0a75cd5f359c964b7e0e4/16:9/w_1280,c_limit/">https://assets.vogue.com/photos/5eb0a75cd5f359c964b7e0e4/16:9/w_1280,c_limit/</a> GettyImages-1162355675.jpg&quot;,<br>   publishedAt: &quot;2020-05-05T00:20:29Z&quot;,<br>   content: &quot;To commemorate a very different first Monday in May this year, Vogue asked some of our favorite stars to create a playlist featuring timeless songs inspired by the theme of this year&#39;s Met gala and the upcoming Costume Institute exhibition, About Time: Fashio… [+2158 chars]&quot;<br>  ))<br> }<br>}</pre><p>Now, we will take some elements from there to form our Article Row</p><p>Wrap the Text element in an HStack and replace the “Hello, World!” string with <em>article.title</em> in order to use the title of the provided article</p><pre>var body: some View {<br><strong>    HStack{</strong><br>        Text(<strong>article.title</strong>)<br>    <strong>}</strong><br>}</pre><p>Let’s add some modifiers to make the text occupy as small as possible, so we can fit more text into our ArticleRow. You can add these via code or via the inspector. If you use the inspector, you should choose the following options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*tjOE7tfQekvta4BORZZyYA.png" /></figure><p>Otherwise, if you’re adding the modifiers directly on the code, it should end up like this</p><pre>Text(article.title)<br> .font(.caption)<br> .fontWeight(.ultraLight)<br> .lineLimit(2)</pre><p>And now, we’re going to add a small thumbnail image to the left side of our row, so this will leave less space for the article title, but having reduced the text size will help here.</p><p>We’re going to add a KFImage object, which takes a URL object in order to download the image. The resizable() and .frame modifiers will provide an optimal size for the UI element.</p><pre>HStack{<br><strong>    KFImage(URL(string: article.imageLink))<br>        .resizable()<br>        .frame(width: 50, height: 50)</strong><br>    <br>    Text(article.title)<br>       .font(.caption)<br>       .fontWeight(.ultraLight)<br>       .lineLimit(2)<br>}</pre><p>You may notice that the image isn’t being shown on the preview, no worries, when we push the image to our watch, we will be able to see it. In the meantime, let’s add a placeholder, so we at least have some visual cue to indicate that the image is being downloaded, as well as some style touches, like <strong>.cornerRadius(3.0)</strong>, which applies rounded corners to our image, so it looks a little bit nicer, as well as adding vertical padding to our HStack so our image has a little bit of vertical space around it.</p><p>Notice the <strong>.scaledToFill()</strong> modifier below <strong>.resizable()</strong>, this modifier takes our image and scales it enough to fit the frame below, while keeping its aspect ratio.</p><pre>HStack{<br>    KFImage(URL(string: article.imageLink))<br>        <strong>.placeholder {<br>            Image(systemName: &quot;arrow.2.circlepath.circle&quot;)<br>               .font(.largeTitle)<br>               .opacity(0.3)<br>         }</strong><br>        .resizable()<br><strong>        .scaledToFill()</strong><br>        .frame(width: 50, height: 50)<br><strong>        .cornerRadius(3.0)</strong></pre><pre>Text(article.title)<br>        .font(.caption)<br>        .fontWeight(.ultraLight)<br>        .lineLimit(2)<br>}<strong>.padding(.vertical)</strong></pre><p>Now, we’re going to get our hands dirty and work on the logic for fetching the actual articles.</p><p>Create a new swift file and name it <strong>ArticleFetcher</strong></p><p>At the very top, let’s import SwiftUI plus the two libraries we’re gonna use to fetch and handle the data easily</p><pre>import SwiftUI<br>import Alamofire<br>import SwiftyJSON</pre><p>Let’s create a public class with the same file name, and let’s make it an ObservableObject, so our ArticleView can use it to fetch the articles from NewsAPI</p><pre>import Foundation<br>import SwiftUI<br>import Alamofire<br>import SwiftyJSON</pre><pre><strong>public class ArticleFetcher: ObservableObject{<br> <br>}</strong></pre><p>Let’s add two published variables. One that will store the List of articles, and another that will tell us if there was an error while fetching the articles.</p><p>A published variable can be accessed by other views, and the views will update when their value changes.</p><pre>import Foundation<br>import SwiftUI<br>import Alamofire<br>import SwiftyJSON</pre><pre>public class ArticleFetcher: ObservableObject{<br><strong>    </strong><a href="http://twitter.com/Published"><strong>@Published</strong></a><strong> var articles: [Article] = []<br>    </strong><a href="http://twitter.com/Published"><strong>@Published</strong></a><strong> var fetchError: Bool = false</strong><br>}</pre><p>Now, we’re going to create the function that fetches the articles. For this, we’ll need our NewsAPI API Key. If you didn’t copy and paste it before closing News API after you created your account, you could just go to <a href="https://newsapi.org/">https://newsapi.org/</a> and login to get your API Key.</p><p>Let’s create a variable containing our API Key</p><pre>import Foundation<br>import SwiftUI<br>import Alamofire<br>import SwiftyJSON</pre><pre>public class ArticleFetcher: ObservableObject{<br>    <a href="http://twitter.com/Published">@Published</a> var articles: [Article] = []<br>    <a href="http://twitter.com/Published">@Published</a> var fetchError: Bool = false<br>    <br><strong>    let myApiKey = “yourAPIkeyHere“</strong><br>}</pre><p>Below that, we’re going to start our function. Create a function named <strong>fetchArticles()</strong>, and in the body, of the function, we’re going to add an AlamoFire request, containing the NewsAPI URL that will deliver the top headlines.</p><pre>import Foundation<br>import SwiftUI<br>import Alamofire<br>import SwiftyJSON</pre><pre>public class ArticleFetcher: ObservableObject{<br>    <a href="http://twitter.com/Published">@Published</a> var articles: [Article] = []<br>    <a href="http://twitter.com/Published">@Published</a> var fetchError: Bool = false<br>    <br>    let myApiKey = “yourAPIkeyHere”<br>    <br><strong>    func fetchArticles(){<br>        AF.request(&quot;</strong><a href="https://newsapi.org/v2/top-headlines?apiKey="><strong>https://newsapi.org/v2/top-headlines?language=en&amp;apiKey=</strong></a><strong>&quot;+myApiKey)<br>    }</strong><br>}</pre><p>Now, we need to take the response as a JSON object and use SwiftyJSON to access the value of the response. We’re going to add a switch statement in there to catch a possible failure, and we will update our published variable <strong><em>fetchError</em></strong> so we can reflect the error in the UI.</p><pre>func fetchArticles(){<br>    AF.request(&quot;<a href="https://newsapi.org/v2/top-headlines?apiKey=">https://newsapi.org/v2/top-headlines?</a><a href="https://newsapi.org/v2/top-headlines?apiKey=">language=en&amp;</a><a href="https://newsapi.org/v2/top-headlines?apiKey=">apiKey=</a>&quot;+myApiKey)<strong>.responseJSON{ response in</strong></pre><pre><strong>switch response.result {<br>         case .success(let value):<br>             let json = JSON(value)<br>                <br>         case .failure(let error):<br>             print(error)<br>             self.fetchError = true</strong></pre><pre><strong>}<br> }</strong><br>}</pre><p>For what comes next, we will do the following</p><ul><li>We will take the array of articles contained in the JSON variable</li><li>We will create an array that will hold Article type objects</li><li>We will iterate over each article, and use the data to create an Article object</li><li>That Article object will be appended to the array that holds our Articles</li><li>When we finish iterating, we will copy the contents of our Article array into the published variable that also holds Articles.</li></ul><pre>func fetchArticles(){<br>  AF.request(&quot;<a href="https://newsapi.org/v2/top-headlines?apiKey=">https://newsapi.org/v2/top-headlines?language=en&amp;apiKey=</a>&quot;+myApiKey).responseJSON{ response in<br>   switch response.result {<br>    case .success(let value):<br>     let json = JSON(value)<br>     <br>     let articles = json[&quot;articles&quot;].array ?? []<br>     var articleArray: [Article] = []<br>     for item in articles {<br>      let title = item[&quot;title&quot;].string ?? &quot;Untitled Article&quot;<br>      let author = item[&quot;author&quot;].string ?? &quot;No author data&quot;<br>      let description = item[&quot;description&quot;].string ?? &quot;No description&quot;<br>      let link = item[&quot;url&quot;].string ?? &quot;&quot;<br>      let imageLink = item[&quot;urlToImage&quot;].string ?? &quot;<a href="https://via.placeholder.com/50x50.png?text=IMG">https://via.placeholder.com/50x50.png?text=IMG</a>&quot;<br>      let publishedAt = item[&quot;publishedAt&quot;].string ?? &quot;No version data&quot;<br>      let content = item[&quot;content&quot;].string ?? &quot;No article content&quot;<br>      let articleItem = Article(title: title, description: description, author: author, link: link, imageLink: imageLink, publishedAt: publishedAt, content: content)<br>      articleArray.append(articleItem)<br>     }<br>     self.articles = articleArray<br>    <br>    case .failure(let error):<br>     print(error)<br>     self.fetchError = true<br>   }<br>  }<br> }</pre><p>As you can see, we provided some fallback values in case that an Article doesn’t contain what we need.</p><p>At the end, ArticleFetcher should look like this</p><pre>import Foundation<br>import SwiftUI<br>import Alamofire<br>import SwiftyJSON</pre><pre>public class ArticleFetcher: ObservableObject{<br> <a href="http://twitter.com/Published">@Published</a> var articles: [Article] = []<br> <a href="http://twitter.com/Published">@Published</a> var fetchError: Bool = false<br> <br> let myApiKey = &quot;yourApiKeyHere&quot;<br> <br> func fetchArticles(){<br>  AF.request(&quot;<a href="https://newsapi.org/v2/top-headlines?apiKey=">https://newsapi.org/v2/top-headlines?language=en&amp;apiKey=</a>&quot;+myApiKey).responseJSON{ response in<br>   switch response.result {<br>    case .success(let value):<br>     let json = JSON(value)<br>     <br>     let articles = json[&quot;articles&quot;].array ?? []<br>     var articleArray: [Article] = []<br>     for item in articles {<br>      let title = item[&quot;title&quot;].string ?? &quot;Untitled Article&quot;<br>      let author = item[&quot;author&quot;].string ?? &quot;No author data&quot;<br>      let description = item[&quot;description&quot;].string ?? &quot;No description&quot;<br>      let link = item[&quot;url&quot;].string ?? &quot;&quot;<br>      let imageLink = item[&quot;urlToImage&quot;].string ?? &quot;<a href="https://via.placeholder.com/50x50.png?text=IMG">https://via.placeholder.com/50x50.png?text=IMG</a>&quot;<br>      let publishedAt = item[&quot;publishedAt&quot;].string ?? &quot;No version data&quot;<br>      let content = item[&quot;content&quot;].string ?? &quot;No article content&quot;<br>      let articleItem = Article(title: title, description: description, author: author, link: link, imageLink: imageLink, publishedAt: publishedAt, content: content)<br>      articleArray.append(articleItem)<br>     }<br>     self.articles = articleArray<br>    <br>    case .failure(let error):<br>     print(error)<br>     self.fetchError = true<br>   }<br>  }<br> }<br>}</pre><p>Now, we’re going to get back on to some UI stuff. Let’s go back to ContentView, we’re going to add a button that takes us to ArticlesView.</p><p>Below the second Text element, let’s add a Spacer() and a NavigationLink with ArticlesView as the destination, wrapping a Text element that says “Start”, or something similar.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack(alignment: .trailing){<br>            Text(&quot;WristNews&quot;)<br>                .font(.title)<br>                .fontWeight(.thin)<br>            <br>            Text(&quot;Daily news, delivered on your wrist.&quot;)<br>                .fontWeight(.thin)<br>                .multilineTextAlignment(.trailing)<br>            <br>            <strong>Spacer()<br>            <br>            NavigationLink(destination: ArticlesView()){<br>                Text(&quot;Start&quot;)<br>            }</strong><br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*8kpGoV5AAW5NHeDmgf1KMw.png" /></figure><p>That Start button will take us to our ArticlesView, where we will now add the List of Articles to populate the View, so let’s go to ArticlesView.</p><p>Right after the struct opens, we’re going to add an ObservedObject variable and name it articleManager, which will be an instance of ArticleFetcher. With it, we can trigger the article fetching from our View, and also access both the List of articles and the possible error that can be displayed.</p><pre>struct ArticlesView: View {<br><strong>    </strong><a href="http://twitter.com/ObservedObject"><strong>@ObservedObject</strong></a><strong> var articleManager = ArticleFetcher()</strong><br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;Articles&quot;)<br>        }<br>    }<br>}</pre><p>Let’s add an onAppear modifier to our VStack, which will let us execute functions when that component appears on the screen. On the onAppear body, we will execute the function that fetches the articles.</p><pre>struct ArticlesView: View {<br>    <a href="http://twitter.com/ObservedObject">@ObservedObject</a> var articleManager = ArticleFetcher()<br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;Articles&quot;)<br>        }<strong>.onAppear{<br>            self.articles.fetchArticles()<br>        }</strong><br>    }<br>}</pre><p>Now, we’re going to add our List of articles into the View. Let’s create a list and pass on to it, the List of articles that articleManager contains. In the body of the List, we will iterate over each Article object, and create an ArticleRow with the article data inside. Just like when we were working on ArticleRow, this time, ArticleRow will take the real data instead of the hardcoded data we used on the Preview struct.</p><pre>struct ArticlesView: View {<br>    <a href="http://twitter.com/ObservedObject">@ObservedObject</a> var articleManager = ArticleFetcher()<br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;Articles&quot;)<br><strong>            List(self.articleManager.articles) { article in<br>                ArticleRow(article: article)<br>            }<br></strong>        }.onAppear{<br>            self.articleManager.fetchArticles()<br>        }<br>    }<br>}</pre><p>We’re going to add some UI elements to catch errors, and provide an option to let the user try to fetch the articles again.</p><p>For that, we’re going to add an <strong>if</strong> statement right under our first Text element. That statement will check for the value of <strong>fetchError</strong>, which will be <strong>false</strong> until an error comes up.</p><p>If <strong>fetchError</strong> is true, that means that an error occurred while trying to fetch the articles, so we’ll add a Text element in there to tell the user that something happened.</p><pre>struct ArticlesView: View {<br>    <a href="http://twitter.com/ObservedObject">@ObservedObject</a> var articleManager = ArticleFetcher()<br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;Articles&quot;)<br>            <strong>if(self.articleManager.fetchError == true)</strong>{<br>            <strong>    Text(&quot;There was an error while fetching your news&quot;)<br>            } else {<br>                List(self.articleManager.articles) { article in<br>                    ArticleRow(article: article)<br>                }<br>            }</strong><br>        }.onAppear{<br>            self.articleManager.fetchArticles()<br>        }<br>    }<br>}</pre><p>Let’s also add in there a button to let the user try to fetch the articles again.</p><pre>struct ArticlesView: View {<br>    <a href="http://twitter.com/ObservedObject">@ObservedObject</a> var articleManager = ArticleFetcher()<br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;Articles&quot;)<br>            if(self.articleManager.fetchError == true){<br>                Text(&quot;There was an error while fetching your news&quot;)<br>                <strong>Button(action:{<br>                    self.articleManager.fetchArticles()<br>                }){<br>                    Text(&quot;Try Again&quot;)<br>                }</strong><br>            } else {<br>                List(self.articleManager.articles) { article in<br>                    ArticleRow(article: article)<br>                }<br>            }<br>        }.onAppear{<br>            self.articleManager.fetchArticles()<br>        }<br>    }<br>}</pre><p>Now, let’s go into <strong>ArticleFetcher</strong> and we’ll switch the value of <strong>fetchError</strong> to <strong>true</strong>, so we can check how our error message looks like in the preview.</p><pre>public class ArticleFetcher: ObservableObject{<br>    <a href="http://twitter.com/Published">@Published</a> var articles: [Article] = []<br>    <a href="http://twitter.com/Published">@Published</a> var fetchError: Bool = <strong>true</strong></pre><p>After doing so, let’s go back to ArticlesView, and let’s remove the first Text element that contains “Articles”, since it’s no longer needed and is somewhat redundant. Resume the preview, and you will see the error message in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*ilpEMfw0SVWir1rZf5k6LQ.png" /></figure><p>To make this look a little bit better, let’s align the text to the center. You can do so via the inspector by tapping on the text, or via code. It should end up like this on code:</p><pre>if(self.articleManager.fetchError){<br>    Text(&quot;There was an error while fetching your news.&quot;)<br><strong>        .multilineTextAlignment(.center)</strong></pre><pre>Button(action:{<br>        self.articleManager.fetchArticles()<br>    }){<br>        Text(&quot;Try Again&quot;)<br>    }<br>} else {<br>    List(self.articleManager.articles) { article in<br>        ArticleRow(article: article)<br>    }<br>}</pre><p>Let’s go back to ArticleFetcher, and turn the <strong>fetchError</strong> value back to false. Also, at the very start of the <strong>fetchArticles</strong> function, let’s set the value to <strong>false</strong>, so the error clears everytime we try to fetch the articles. Don’t worry, it’ll turn back to <strong>true</strong> if we come across an error again.</p><pre>public class ArticleFetcher: ObservableObject{<br>    <a href="http://twitter.com/Published">@Published</a> var articles: [Article] = []<br>    <a href="http://twitter.com/Published">@Published</a> var fetchError: Bool = <strong>false</strong><br>    <br>    let myApiKey = &quot;yourApiKeyHere&quot;<br>    <br>    func fetchArticles(){<br><strong>        self.fetchError = false</strong><br>        AF.request(&quot;<a href="https://newsapi.org/v2/top-headlines?language=en&amp;apiKey=">https://newsapi.org/v2/top-headlines?language=en&amp;apiKey=</a>&quot;+myApiKey).responseJSON{ response in</pre><pre>...</pre><p>Now, we’re almost there! The last step will be creating a detailed view so we can tap on our articles and see them in detail, and we will be ready to wrap this up and push the App to our Apple Watch!</p><p>Create a new SwiftUI View and name it ArticleDetail. Same as with ArticleRow, we will require an Article object here, so let’s add that in there, and let’s copy the same hardcoded data we used on the ArticleRow preview over here as well. We also will import Kingfisher to show an image in here as well, but this time, it’s going to be a little bit bigger.</p><pre>import SwiftUI<br>import Kingfisher<br>import struct Kingfisher.KFImage</pre><pre>struct ArticleDetail: View {<br>    var article: Article<br>    <br>    var body: some View {<br>        Text(&quot;Hello, World!&quot;)<br>    }<br>}</pre><pre>struct ArticleDetail_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ArticleDetail(article: Article(<br>            title: &quot;Rosalía Shares Her All-Time Favorite Songs in a Met Gala–Themed Playlist - Vogue&quot;,<br>            description: &quot;This playlist is a celebratory playlist for the Met, with nods to my all-time favorite songs, sounds, artists, and references. It has not been possible to celebrate the Met as God intended, but we can celebrate it in our own way from home.&quot;,<br>            author: &quot;Estelle Tang&quot;,<br>            link:&quot;<a href="https://www.vogue.com/article/rosalia-met-gala-about-time-playlist">https://www.vogue.com/article/rosalia-met-gala-about-time-playlist</a>&quot;,<br>            imageLink: &quot;<a href="https://assets.vogue.com/photos/5eb0a75cd5f359c964b7e0e4/16:9/w_1280,c_limit/">https://assets.vogue.com/photos/5eb0a75cd5f359c964b7e0e4/16:9/w_1280,c_limit/</a> GettyImages-1162355675.jpg&quot;,<br>            publishedAt: &quot;2020-05-05T00:20:29Z&quot;,<br>            content: &quot;To commemorate a very different first Monday in May this year, Vogue asked some of our favorite stars to create a playlist featuring timeless songs inspired by the theme of this year&#39;s Met gala and the upcoming Costume Institute exhibition, About Time: Fashio… [+2158 chars]&quot;<br>        ))<br>    }<br>}</pre><p>Replace “Hello, world!” by article.title, and, below it, add another Text element that contains the author’s name. Let’s make this last text element ultraThin, so it differentiates itself from the title. Wrap everything in a VStack, and then, wrap the VStack inside a ScrollView. This will let us scroll up or down a view that overflows the screen.</p><pre>var body: some View {<br> ScrollView{<br>  VStack(alignment: .leading){<br>   <strong>Text(article.title)<br>    .font(.headline)<br>    .fixedSize(horizontal: false, vertical: true)<br>    <br>   Text(&quot;By \(article.author)&quot;)<br>    .fontWeight(.ultraLight)</strong><br>  }<br> }<br>}</pre><p>Below the author’s name, we’ll add the image. This time, I won’t add a placeholder, since it’s not immediately obvious we’re expecting an image here, different from the ArticleRow View. It’s up to you though, if you want to add a placeholder, you can take some code from ArticleRow.</p><p>After that, let’s add a Divider(), and both the article description and content. We’ll add some modifiers to both of them, to make the text occupy as less space as possible, and the last one to not truncate the text.</p><pre>var body: some View {<br> ScrollView{<br>  VStack(alignment: .leading){<br>   Text(article.title)<br>    .font(.headline)<br>    .fixedSize(horizontal: false, vertical: true)<br>    <br>   Text(&quot;By \(article.author)&quot;)<br>    .fontWeight(.ultraLight)</pre><pre><strong>Divider()</strong><br>    <br>   Text(article.description)<br>    .font(.caption)<br>    .fontWeight(.ultraLight)<br>    <strong>.fixedSize(horizontal: false, vertical: true)</strong><br>    <br>   Text(article.content)<br>    .font(.caption)<br>    .fontWeight(.ultraLight)<br><strong>    .fixedSize(horizontal: false, vertical: true)</strong><br>  }<br> }<br>}</pre><p>Finally, let’s add another divider, and two more text elements. One to show the date of publication, and the last one to provide a link to the full story.</p><pre>var body: some View {<br> ScrollView{<br>  VStack(alignment: .leading){<br>   Text(article.title)<br>    .font(.headline)<br>    .fixedSize(horizontal: false, vertical: true)<br>                <br>   Text(&quot;By \(article.author)&quot;)<br>    .fontWeight(.ultraLight)<br>                <br>   KFImage(URL(string: article.imageLink))<br>    .resizable()<br>    .scaledToFit()<br>                <br>   Divider()<br>                <br>   Text(article.description)<br>    .font(.caption)<br>    .fontWeight(.ultraLight)<br>    .fixedSize(horizontal: false, vertical: true)<br>                <br>   Text(article.content)<br>    .font(.caption)<br>    .fontWeight(.ultraLight)<br>    .fixedSize(horizontal: false, vertical: true)<br>                <br><strong>   Divider()<br>                <br>   Text(&quot;Published at \(article.publishedAt)&quot;)<br>    .font(.caption)<br>    .fontWeight(.ultraLight)<br>    .fixedSize(horizontal: false, vertical: true)<br>                <br>   Text(&quot;Read the full story in: \(article.link)&quot;)<br>    .font(.caption)<br>    .fontWeight(.ultraLight)<br>    .fixedSize(horizontal: false, vertical: true)<br>    .padding(.top)<br></strong>    }<br>  }<br>}</pre><p>Now, for the final act, we’re going to link the ArticleRow View to the ArticleDetail View, and we will have completed the App!</p><p>Let’s go back on to ArticlesView. On the List of articles, we’ll wrap ArticleRow inside a NavigationLink, and let’s set it’s destination to ArticleDetail, while providing the same article we provide to ArticleRow.</p><pre>List(self.articleManager.articles) { article in<br>    <strong>NavigationLink(destination: ArticleDetail(article: article)){</strong><br>        ArticleRow(article: article)<br>    <strong>}</strong><br>}</pre><p>And we have finished our App! Now, get your Apple Watch, iPhone, Lightning Cable and plug your iPhone to your Mac.</p><p>Wait a little bit until it’s detected by Xcode.</p><p>Right above the editor, tap on the active scheme</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*dVle2u2L3sbVAUkbEC_Lqg.png" /></figure><p>And at the very top of the List, you should see your Apple Watch via your iPhone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4YpbIpdnIAxfbUmGBIxWQ.png" /></figure><p>Then, tap on the Play button to finally push the App on to your Apple Watch!</p><p>If this is the first time you do this, most likely you will get an error. Worry not! The App is installed on your Apple Watch, but you have to allow it to run. Press the Digital Crown to open the app drawer, and look for a suspicious icon that looks like a White Crosshair on Gray Background, or like some concentric circles with a cross in the middle. That’s your App.</p><p>When you open it, you should see a small message asking for permission to run the App. Tap on Allow, and enjoy!</p><p>I hope you’ve enjoyed this tutorial as much as I enjoyed writing it. Building WatchOS apps with SwiftUI is fun and easy, and it’s amazing how we can do a lot of stuff on a tiny computer that sits on our wrist.</p><p>If you have time, feel free to expand your news app! Add more views, change the ones we have a bit, alter the order of the Text elements, and experiment with it!</p><blockquote>Thanks for getting to the end of it with me!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68981acf615f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/macoclock/making-a-watchos-app-with-swiftui-from-scratch-with-data-fetching-68981acf615f">Making a WatchOS app with SwiftUI from scratch, with data fetching</a> was originally published in <a href="https://medium.com/macoclock">Mac O’Clock</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>