Build your first Swift App
Building a random cat image generator iOS app using SwiftUI from scratch
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.)
- 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.
- Now, Xcode provides us with a lotta options for starter templates. We will select the simple ol' iOS
App
and click next.
Let's start filling this information out
Product Name
: Give your app a nameOrganization 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, andLanguage
: Swift.
๐คNote: you can read more about them here(I insist๐)
- 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)
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 withhttps://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
}
}
- 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๐
- 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.
- 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!