How to Add External Libraries to a SwiftUI Project Using Swift Package Manager

In this post we are going to look at how we can add a Swift package to our SwiftUI Project. Let’s start by going to the Swift Package Index website and searching through the libraries. For this post we are going to use the SwiftUICharts package to add to our project.

SwiftUICharts is an amazing library that makes it super easy to get beautifully animated charts into your SwiftUI project.

Now that we have picked the library we want to add to our project, we now need to click on the copy button under the SwiftUICharts title. This copies the link to SwiftUICharts GitHub so that we can download the package to our project.

Now that we have our link to SwiftUICharts repo, we will need to go to our Xcode project and click on File > Swift Packages > Add Package Dependency and then paste in the repo’s url: https://github.com/AppPear/ChartView

Once you click on the next button, you will then have to choose what version, branch or commit from the package you would like to use.

Here we will not mess with any of the options and just click on the next button. This will now download the package into your Xcode project. Once downloaded, we will make sure our package is selected and click on the finish button.

Now we should see that our package has been successfully added to our project.

Thats all there is too it!

From here we can import the SwiftUICharts library into a file and start using all the amazing charts and animations SwiftUICharts has to offer.

If you would like a deeper dive into Swift Package Manager I would recommend checking out this great article by @Shashikant86

Thanks for reading and happy coding!

How to Make a Custom HUD View in SwiftUI

In this post we are going to make a custom HUD view with a timer. The timer will dismiss our HUD view after about a second. Our HUD view will be similar to the pop up view we see on our screen when we put our phone into silent mode.

Let’s jump right in by creating a new SwiftUI file and naming it HUDView. Next we are going to copy the code below into our HUDView.swift file.

import SwiftUI

struct HUDView<Content: View>: View {
    var content: Content
    @ViewBuilder var body: some View {
        content
            .padding(.horizontal, 10)
            .padding(10)
            .background(
                Capsule()
                    .foregroundColor(Color.white)
                    .shadow(color: Color(.black).opacity(0.10), radius: 10, x: 0, y: 5)
            )
    }
}

struct HUD_Previews: PreviewProvider {
    static var previews: some View {
        HUDView(content: Text("HI"))
    }
}

Above we created a HUD view that takes in a view as a variable and then presents that view when the HUD appears. We also stylized our HUD to look like the pill shaped silent mode view in the image above. Now that we have created our HUD lets go add it to our ContentView.swift file.

In our ContentView file we will replace the boilerplate code with the code below.

import SwiftUI

struct ContentView: View {
    var body: some View {
        HUDView(content: Text("Hello, World!"))
    }
}

In our preview screen we should see a pill shaped view with a text view saying “Hello World!”.

Next we will need to move our HUD view from the middle of our view to the top of our view. Let’s take a look at the example below to see how we can setup our HUD view.

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .top) {
            NavigationView {
                Button("Save") {
                    
                }
                .navigationTitle("Home")
            }
            HUDView(content: Text("Save"))
        }
    }
}

As you can see in the code above we added a ZStack to keep our HUD view aligned to the top and above the content on screen. Next we added a save button which will show our HUD view when we tap on the button. Lastly we added a NavigationView so we can have a navigation title on our screen for some style points.

Now when our save button is tapped we will want to present our HUDView. Then after 1.5 seconds we will have our HUD dismiss itself. To do this let us add the code below to our ContentView file.

import SwiftUI

struct ContentView: View {
    @State private var showHUD = false
    var body: some View {
        ZStack(alignment: .top) {
            NavigationView {
                Button("Save") {
                    withAnimation {
                        self.showHUD.toggle()
                        dismissHUD()
                    }
                }
                .navigationTitle("Home")
            }
            
            HUDView(content: Text("Save"))
                .offset(y: showHUD ? 0 : -100)
                .animation(.spring())
        }
    }

    func dismissHUD() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            self.showHUD = false
        }
    }

}

Above we added a @State property to track when we will show and hide the HUD view. Then we added the dismissHUD() function so that we can dismiss the HUD view after 1.5 seconds(feel free to change the time to dismiss to whatever you like best). Lastly we added an .offset and .animation(.spring()) modifier to our HUD view. We added the .offset modifier so we can hide the HUD view offscreen when not being shown. We also added a spring animation to give our HUD some bounce when entering the view from off screen. Now when we run our app and press our save button, we should see our HUD appear and then disappear after 1.5 seconds.

Thanks for reading! Hope this helps you in your next SwiftUI project.

Happy Coding!

Iron man GIF - Find on GIFER

Picker View Styles in SwiftUI

In this post we are going to take a look at the different ways we can style a picker view in our SwiftUI project. Let’s first setup a simple picker view like in the example below.

    var arrayOfNames = ["Tom", "Nick", "Tony", "Dylan"]
    @State private var selectedIndex = 0
    
    var body: some View {
        Picker("Names", selection: $selectedIndex) {
            ForEach(0 ..< arrayOfNames.count) {
                Text(self.arrayOfNames[$0])
            }
        }
    }
}

Above we created a basic picker view with four names to choose from. Now let us change the style of our picker to be included in a Form.

    var arrayOfNames = ["Tom", "Nick", "Tony", "Dylan"]
    @State private var selectedIndex = 0
    
    var body: some View {
        NavigationView {
            Form {
                Picker("Names", selection: $selectedIndex) {
                    ForEach(0 ..< arrayOfNames.count) {
                        Text(self.arrayOfNames[$0])
                    }
                }
            }
        }
    }
}

In the example above is wrapped our code in a NavigationView and a Form. This changes our picker view style so that it segues us to another view to make our selection. This is great for a picker that has many options to choose from. But let’s say we didn’t want to segue to another view to see our options.

Let’s see how we can implement a segmented picker view style.

    var arrayOfNames = ["Tom", "Nick", "Tony", "Dylan"]
    @State private var selectedIndex = 0
    
    var body: some View {
        NavigationView {
            Form {
                Picker("Names", selection: $selectedIndex) {
                    ForEach(0 ..< arrayOfNames.count) {
                        Text(self.arrayOfNames[$0])
                    }
                }.pickerStyle(SegmentedPickerStyle())
            }
        }
    }

By just adding .pickerStyle(SegmentedPickerStyle()) to our picker view, SwiftUI gives us a segmented style picker view with minimal change to our code.

Let’s say we don’t want either of these styles. What if we wanted a picker view like we originally had in our first example. We can easily do this by switching our picker style to .pickerStyle(WheelPickerStyle()).

I hope this helps you in your next SwiftUI Project.

Thanks for reading and happy coding! ⛏⛏⛏

No Such Module Found (M1 Macbook Pro Solution)

Recently I have been working on a new project with my new M1 Macbook Pro. In this project I needed to use third party libraries such as FBSDKCoreKit (Facebook) so the user could sign in with their Facebook account. The problem I ran into was that no matter what I did the Cocoapods I loaded into my project would not run. Xcode would give me error messages such as “No such module found” or “module ‘FBSDKCoreKit’ not found“.

After hours of googling and looking at Github issues on the topic, I found the solution. If you are running into this problem on a M1 Mac you need to open Xcode using Rosetta. What is Rosetta? Without getting too technical Rosetta allows the new M1 Mac’s to run x86 architecture apps. For a deeper dive into Rosetta check out the link here. If you need to install Rosetta 2 on your M1 Mac click on this link here and follow the tutorial.

Now to fix this issue we need to go into our Finder > Applications > and right click (command ⌘ + click) on Xcode. Then we need to select “Get Info

Once we have the “Get Info” window opened, we then need to click on “Open using Rosetta

Now if we relaunch our Xcode and build our project we shouldn’t see anymore errors like “Module not Found“. I hope this helps save you some time and headaches.

Thanks for reading. Happy Coding!

How to Add an AppDelegate to a SwiftUI Project

When you create a new SwiftUI project, you will see that we no longer have the AppDelegate.swift file. This doesn’t mean we don’t need or use the AppDelegate file anymore. If we want to implement something like push notifications we will need to use an AppDelegate in our SwiftUI app. Let’s take a look at how we can add an AppDelegate file to our SwiftUI project.

First we will need to create a new swift file and name it AppDelegate. Now inside of our new AppDelegate file we will need to copy and paste the code below (Feel free to add any AppDelegate functions you need for your project).

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        // Your Code Here!
        return true
    }
}

Now that we have our AppDelegate created, we will need to tell our app to use the AppDelegate.swift file. Let us navigate over to the App file in our project. This file is named after your project with “App” at the end. In this example my file is named AppDelegateBlogProjectApp.swift (Not the best name in the world 🤣).

In this file we will create and wrap our AppDelegate property in the UIApplicationDelegateAdaptor property wrapper. This tells SwiftUI we want to use the AppDelegate file we just created.

@main
struct AppDelegateBlogProject: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

That is all we need to make an AppDelegate in a SwiftUI project!

Thanks for reading!

@Appstorage in SwiftUI

Appstorage is a property wrapper for getting stored values from UserDefaults in SwiftUI. We use @Appstorage too reload our body view property whenever the value changes of our UserDefaults. This keeps our view up to date with the data that we have stored. Let’s take a look at an example on how we can use @Appstorage in our SwiftUI project.

import SwiftUI

struct ContentView: View {
    @AppStorage("isCookieTime") var isCookieTime = false
    
    var body: some View {
            Toggle("Cookie time", isOn: $isCookieTime)
        .padding()
    }
}

In the example above we have a Toggle view for “Cookie time” 🍪. We use our @AppStorage property to watch our isCookieTime variable. If the value changes it is then stored in our UserDefaults. Now our toggle will show the stored value depending on the @AppStorage.

A example of where I use @AppStorage is for storing things like a users settings options in a settings screen of an app. I hope this helps explain how to use @AppStorage in SwiftUI.

Thanks for reading and happy coding.

How to Make a Code Snippet in Xcode

Code snippets are shortcuts to blocks of boilerplate code that we use most often when programming. Xcode allows us to add custom snippets to the many pre-existing snippets that Apple provides. Let’s see how we can make a code snippet out of the following code below.

DispatchQueue.main.async {
                    
                }

You might be familiar with the example code above. This block of code is used to make sure things like network calls are made on the main thread and not on a background thread. Let’s make a code snippet of this so we don’t have to type the whole thing out every time we want to use it.

If we highlight the code and then right click (⌘ + click) you will see an option to “Create Code Snippet”.

Once we click on “Create Code Snippet” a window will popup and prompt us to customize our code snippet.

First we will name our snippet “Dispatch Main Queue” (Feel free to name it whatever you want 😄). Now we will leave everything else the same except the “Completion” section. In the “Completion” textfield we will type in “dpm”.

What this does is every time we type “dpm” Xcode will prompt us in the autocompletion to see if we want to use our code snippet! So from now on anytime we want to put something on the main thread all we have to do is type “dpm” and we get our code snippet we just created.

Just like that we have made a code snippet and saved ourselves time by never having to type out all that code ever again! Feel free to make code snippets of any block of code your tired of typing out! Embrace your laziness!

Thanks for reading and I hope this helps your coding productivity.

Happy coding!

Texas Tribune Nerds - What I Learned at The Texas Tribune

How to Make a Tab Bar View in SwiftUI

In this post we are going to take a look at how we can add a tab bar view to our SwiftUI app. Tab bar views are used to display a view when the tab item is selected. For this example we will simply have two tab views that will show a text view with a different background color. Let’s start by creating our example views that we will assign to our tab bar.

import SwiftUI
struct FirstView: View {
    var body: some View {
        ZStack {
            Color(.green)
            Text("First View")
                .font(.title)
        }.ignoresSafeArea()
    }
}
struct SecondView: View {
    var body: some View {
        ZStack {
            Color(.blue)
            Text("Second View")
                .font(.title)
                .foregroundColor(.white)
        }.ignoresSafeArea()
    }
}

As you can see we have created two views with just a text view and a color for the background. Now that we have our views setup we can go to our ContentView.swift file and make our tab bar view.

import SwiftUI
struct ContentView: View {
    var body: some View {
        TabView {
            FirstView()
                .tabItem {
                    Image(systemName: "1.circle.fill")
                    Text("First View")
                }
        
            SecondView()
                .tabItem {
                    Image(systemName: "2.circle.fill")
                    Text("Second View")
                }
        }
    }
}

As you can see in the example above all we needed to do was make a TabView and initialize our two views as a .tabItem. Inside of our .tabItem we added an image and the title to be displayed on our tab. Now if we run our application we should see our app look like the images below.

I hope this helps you on your next SwiftUI project.

Thanks for reading and happy coding!

How to Fetch JSON Data from APIs in SwiftUI

In this post we are going to take a look at how we can get JSON data from an API and show it in a list view in SwiftUI. Let’s jump right in a get started by creating a new SwiftUI project.

In this project we are going to be using the JSONPlaceholder API. JSONPlaceholder is a free to use fake REST API for testing and prototyping.

We will be fetching our data from the https://jsonplaceholder.typicode.com/posts/1/comments URL.

Now in our Xcode project we will create a model file and name it Comments. This will be our model for the data we are going to want to show in our list view.

import SwiftUI

struct Comments: Codable, Identifiable {
    let id = UUID()
    let name: String
    let email: String
    let body: String
    
}

In the code above we made a simple struct that conforms to the Codable and Identifiable protocols. Codable is used for decoding and encoding the JSON data we get from our API call. Identifiable is used to help us make a unique identifier for our Comments object so our app can keep track of it. In our example it helps us to keep track of our comments and display them in the right order for our list view. We also have added the name, email, and body properties that will be set to the JSON data we get back from our API call.

Next we will add a new file where we will create the call to our API to get our JSON data. Let’s start by creating a new file and naming it commentViewModel. Then we will add the following code to our commentViewModel file.

import Foundation

class apiCall {
    func getUserComments(completion:@escaping ([Comments]) -> ()) {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1/comments") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let comments = try! JSONDecoder().decode([Comments].self, from: data!)
            print(comments)
            
            DispatchQueue.main.async {
                completion(comments)
            }
        }
        .resume()
    }
}

Above all we did was create a class called apiCall and added a function called getUserComments(). In our getUserComments() function we first make a guard let statement on our url variable. This is to check to make sure we have a valid URL otherwise the function will stop there and not execute the rest of the code.

Next we use URLSession to make our call to get the data from the URL. Inside of our URLSession closure we create a new variable called comments and we assign the decoded JSON to our variable. Then we use DispatchQueue to make sure we are running this API call on the main thread and not a background thread of our app. On completion of retrieving our data we then assigns the data to our comments variable. Lastly we can’t forget the .resume() function at the end of your URLSession curly brace. If you forget this the function will never run the API call to the URL.

Now that we have our view model setup lets go into ContentView file and add the following code to our file.

import SwiftUI

struct ContentView: View {
    //1.
    @State var comments = [Comments]()
    
    var body: some View {
        NavigationView {
            //3.
            List(comments) { comment in
                VStack(alignment: .leading) {
                    Text(comment.name)
                        .font(.title)
                        .fontWeight(.bold)
                    Text(comment.email)
                        .font(.subheadline)
                        .fontWeight(.bold)
                    Text(comment.body)
                        .font(.body)
                }
                
            }
            //2.
            .onAppear() {
                apiCall().getUserComments { (comments) in
                    self.comments = comments
                }
            }.navigationTitle("Comments")
        }
    }
}
  1. First we created a @State variable that takes in an array of our Comments model.
  2. Next we added the .onAppear() function. This is were we make our call to our API to get our data and then set it to the comments variable we just created.
  3. Then in our list view we pass in the data that we have in our Comments array

Now we can go and run our app. We should see something like the image below.

Thats all we need to fetch and show JSON data in SwiftUI. Thanks for reading!

Happy Coding!

data numbers GIF

How to Make a Phone Call using SwiftUI

Making a phone call from a SwiftUI app is easy and only takes a few lines of code to implement. All we need to do is setup a button that will open the phone app and make a phone call with a phone number we pass in.

Let’s look at some code below to see what we need to implement this.


struct ContentView: View {

    var phoneNumber = "718-555-5555"

    var body: some View {
        VStack {
            Button(action: {
                let phone = "tel://"
                let phoneNumberformatted = phone + phoneNumber
                guard let url = URL(string: phoneNumberformatted) else { return }
                UIApplication.shared.open(url)
               }) {
               Text(phoneNumber)
                .foregroundColor(.blue)
            }
        }
    }
}

In the example above we first create a string variable with the phone number we would like to use. Next we create a button and within the action of our button we format the phone number to our URL. The “tel://” is the url needed to tell our device to open the phone app and make a call. (We can use the same code above to open other apps on our device. For example if we wanted to open the mail app we just need to replace the url with messages:// instead of tel://)

Next we have a guard let statement to check to see if we have a formatted phone number. Then we use UIApplication to open the phone app and make a call using the url with the phone number we passed in. Lastly we set our button label to show the phone number we want to call.

(Side note: We will need to run this on a device to test because the simulator can not make phone calls.)

That is all that we need to make a phone call from our SwiftUI app. Hope this helps you on your next SwiftUI project!

Thanks for reading!

☎️📱🤳Happy coding ☎️📱🤳