Build your first Swift App

Build your first Swift App

Building a random cat image generator iOS app using SwiftUI from scratch

ยท

5 min read

Today we'll be building this cat image generator app with the latest version of Swift and Xcode:

So fire up your Xcode and let's get started!๐Ÿ”ฅ

๐Ÿ‘‰ Here's the completed code: GitHub

๐Ÿ‘‰ And this is where we will get our images from: unsplash


But before we start, I just want to quickly share a few things with y'all:

Why I started learning Swift?๐Ÿคทโ€โ™€๏ธ

I started learning Swift, out of sheer curiosity. We all can agreeโ€”Apple apps are so smooth and nice to use, and Swift is the language igniting them all. I found Swift so pretty and elegant, and honestly, it came so naturally to me. It's very intuitive and easy to learn, especially if you have worked with any other language, even a bit.

That was a bit about me, now let's get the basics out of our way too.

What's SwiftUI?๐Ÿค”

SwiftUI was launched in 2019 by apple to build user interfaces for apps on Apple platforms.

SwiftUI is a closed source framework built on top of Swift, which in itself is open source from apple. You could also use UIKit to build iOS apps but that framework uses imperative programming (think Android development using java/kotlin) while SwiftUI is declarative like React/Flutter.

(quoting @dramikei ๐Ÿ˜›)


Alright! Enough talking, let's get our hands dirty pretty with some Swift coding!๐Ÿ˜Šโœจ

Step 1: Setting up โš™๏ธ

We will start with creating a new project.

(You can follow me or alternatively refer these apple docs.)

  1. First, open Xcode. If you don't have it, you can simply get it from apple app store.
    Once launched, choose "Create New Project" to start a new project.

  1. Now, Xcode provides us with a lotta options for starter templates. We will select the simple ol' iOS App and click next.

  1. Let's start filling this information out

    • Product Name: Give your app a name

    • Organization Identifier: It's a reverse domain name, to identify your organization. So, make sure you change it to something unique.

    • Interface we will use SwiftUI, and

    • Language: Swift.

๐Ÿค—Note: you can read more about them here(I insist๐Ÿ‘€)

  1. Once you add all the details, click "Next". Select a location on your Mac to save the project and click "Create".

Xcode welcomes you with a simple "Hello, world!" app.๐Ÿ‘‹

Step 1 done โœ…

Now, let's start customizing our app.

Step 2: Building UI ๐ŸŽ€

Building UI here is as easy as dragging and dropping components. Alternatively, you can always type them up as well (if that's what you prefer๐Ÿ‘€).

For our cat image generator, we just need two components:

  • An image,

  • A button (to load the next image)

  1. To display images from the internet, we'll use something called AsyncImage. Search it from library and drop it in your file. Replace the URL string with https://source.unsplash.com/random/?cat

    AsyncImage loads and displays an image asynchronously from the given URL.

๐Ÿค— Note: We use AsyncImage only when we are adding image from the internet (or a URL). If you want to add image from your local system, we can use a simple Image component.

Next let's add certain properties to make sure images of all sizes fit screens of all sizes without getting stretched or distorted ๐Ÿฅด:

  • resizable(): Makes the image resizable.

  • aspectRatio(contentMode: .fit): Ensures the image fits the screen without distortion.

  • placeholder: Displays a placeholder while the image is loading.

VStack {
        AsyncImage(url: URL(string: "https://source.unsplash.com/random/?cat")) { image in
                   image
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                    } placeholder: {
                        Color.gray
                    }
                }
  1. Now, we'll add a button to load up the next image. You can simply drag and drop a Button under the AsyncImage. Inside the {}, we'll specify the action that's to be performed on button click.

Try adding print("Hello world") and see what you get in the terminal when you click the button :)

Button("Next") {
        print("Hello world") 
  }

Right now, it's is a pretty bad looking button. But nothing that some colors, padding and rounded corners can't fix ๐Ÿ˜‰.

We can change those properties like this:

Button("Next") {
        print("Hello world") 
           }
                .foregroundColor(.white)
                .padding()
                .background(Color.blue)
                .cornerRadius(10)
                .padding(.top, 20)

๐Ÿค— Note: You might have observed that both of our components are wrapped up in a VStack. A VStack, as the name suggests, stacks everything inside it vertically in a column. Similary, SwiftUI offers a HStack and a ZStack too.

In the end, you will end up with something looking like:

Step 3: Fixing the button ๐Ÿ–ฒ๏ธ

As of now, nothing really happens when we click the next button. Let's fix that๐Ÿ”ง

We need to update the URL of the AsyncImage each time the button is pressed. We can do this by specifying a random id (that changes with each click) at the end of our URL like this:

https://source.unsplash.com/random/?cat&/randomshitreallyidkwhatimtyping

Let's see how๐Ÿ‘‡

  1. But first, let's create a separate variable for the URL. And replace in AsyncImage.
struct ContentView: View {
    @State private var imageURL = URL(string: "https://source.unsplash.com/random/?cat")!

```
AsyncImage(url: imageURL) { image in
```

๐Ÿค— Note: You must have observed we added @State while declaring our variable. So, @State is a property decorator that automatically updates the view whenever the value of the variable changes. If your a keen person (like me๐Ÿ‘€), you can read more about it here.

  1. Now, Let's define this function that generates a new random URL inside our ContentView struct:
func changeImage() {
    self.imageURL = URL(string: "https://source.unsplash.com/random/?cat&/\(UUID().uuidString)")!
}

In here, we appended a unique random UUID string generated by UUID().uuidString to the end of our base URL.

Now all that's left is to call changeImage() every time the button is clicked. Like this๐Ÿ‘‡

Button("Next") {
                changeImage()
            }

Go ahead and run your app. And you'll end up with pretty cool cat images๐Ÿ˜Ž


We did it! ๐Ÿ™Œ

Hope you had fun on this new journey with me <3

See you on the next one!!


โค๏ธFollow me on Twitter to know more about me!

๐Ÿ’• Also subscribe to my Youtube Channel!

ย