How to Know When Your App Becomes Active or Inactive in SwiftUI

Recently I was working on a SwiftUI project were I needed to know when my app became active from being in the background. Like most things in SwiftUI, I found out that this was really simple to implement in my project.

In SwiftUI we have a environment element called scenePhase. What scenePhase allows us to do is monitor if the app is Active, Inactive, or in the Background. Lets take a look at how we can use this in our project.

The first thing we will need to do is add the following variable to your code:

@Environment(\.scenePhase) var scenePhase

This Environment variable is the key to monitoring what state your app is in. Next we will add an .onChange modifier to our view. This will allow us to see when our apps state has changed and then act on that change. Let’s now take a look at how I used the scenePhase variable to reload a specific view when my app became active again.

struct TodayWatchView: View {
    @StateObject var viewModel = TodayWatchViewModel()
    
    // 1) added scenePhase variable
    @Environment(\.scenePhase) var scenePhase
    
    var body: some View {
        ZStack {
            VStack {
                if !viewModel.isHolidaysEmpty {
                    List(viewModel.holidays) { holiday in
                        if holiday.url == "" {
                            Text("\(holiday.name)")
                                .font(.headline)
                                .bold()
                        } else {
                            NavigationLink(holiday.name, destination: HolidayWatchDetailView(holiday: holiday))
                        }
                    }
                } else {
                    EmptyState(message: "There was an issue loading Today's Holidays!\n Try again later")
                }
            }
            
            // 2)
            // Reload data when app becomes active!!
            .onChange(of: scenePhase) { newPhase in
                if newPhase == .inactive {
                    print("Inactive")
                } else if newPhase == .active {
                    viewModel.getHolidays()
                } else if newPhase == .background {
                    print("Background")
                }
            }
            .navigationTitle("Today Is....")
            .alert(item: $viewModel.alertItem) { alertItem in
                Alert.init(title: alertItem.title, message: alertItem.message, dismissButton: alertItem.dismissButton)
            }
            .onAppear {
                viewModel.getHolidays()
            }
            if viewModel.isLoading {
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle(tint: .gray))
                    .scaleEffect(2, anchor: .center)
            }
        }
    }
}

I hope this gives you a better understanding of how you can monitor your app and run functions depending on your apps state.

Thanks for reading and happy coding!!! πŸ‘¨πŸ»β€πŸ’»πŸ‘¨πŸ»β€πŸ’»πŸ‘¨πŸ»β€πŸ’»

“Failed to initialize client context with error”: A Error When Trying to Run a Widget in the Xcode Simulator (M1 Macs)

This is a short post about an issue I recently had with updating a widget for a SwiftUI project. I kept getting a weird error every time I tried to run a widget target in the simulator. The error read “Failed to initialize client context with error“. This was followed by a crazy long error message spit out by the debug console in Xcode. I googled everything and I finally found the solution! (Note: This only happened on my M1 Mac)

What you need to do to fix this error is toggle off the “Open using Rosetta” button. To do that you need to right click on the Xcode app icon and go to “Get Info”. In the Get Info window you are going to want to toggle off the “Open using Rosetta” button. Now if you quit Xcode and reopen, you shouldn’t see that error pop up again. Go re-run the widget in the simulator and VOILΓ€!

Until Apple fixes all the weird errors with supporting both Intel and M1 chips for Xcode, you might need to toggle on and off “Open using Rosetta“.

I really hope this helps you from losing your mind googling for an answer to this solution!

Thanks for reading!

How to Use AsyncImage in SwiftUI 3

Recently Apple has announced AsyncImage at WWDC 2021. This makes loading images from a URL very easy in SwiftUI projects supporting iOS 15 and above. Let’s take a look at an example below.

If we want to load an image from a URL, all we need to do is add the following line of code.

AsyncImage(url: https://i1.wp.com/swifttom.com/wp-content/uploads/2019/10/img_8186-2.jpg?resize=338%2C452&ssl=1)

That’s it! This is all the work we have to do to load an image from a URL! The only problem here is the URL image will most likely take up the whole screen because we didn’t set the image modifiers. We also would want some sort of placeholder image while the URL image loads. No worries, AsyncImage has us covered.

By adding initializers to our AsyncImage, we can have a placeholder while the image is loading and style our image once is has loaded.

            AsyncImage(
                url:https://i1.wp.com/swifttom.com/wp-content/uploads/2019/10/img_8186-2.jpg?resize=338%2C452&ssl=1,
                content: { image in
                    image.resizable()
                         .scaledToFit()
                         .frame(maxWidth: 100, maxHeight: 100)
                },
                placeholder: {
                    ProgressView()
                }
            )

In the example above we have added a content parameter to our AsyncImage. This allows us to set the image modifiers to give our image styling. We also added a placeholder parameter which allows us to show a view as a placeholder until our image has loaded. In the example above we are using a ProgressView as our placeholder until the image loads.

I hope you find this useful in your next SwiftUI 3 projects! Happy coding!! πŸŒπŸ“ΈπŸ€³

“ARCHS[@]: unbound variable” error in SwiftUI Project

Recently I ran into an error when trying to run a SwiftUI Project on my iPhone. I’m running this project on a M1 Macbook Pro. The error seemed to start happening when my project started using certain Cocoapods. The error reads “ARCHS[@]: unbound variable“.

To fix this error all you need to do is navigate to the Project File > Info > Excluded Architecture. If in Excluded Architecture you see arm64, all you need to do is remove the arm64 and reload your Xcode project.

Hope this quick post helps anyone struggling with this weird error in your SwiftUI project. If this doesn’t help please check out this stack overflow post.

Happy coding!

How to Make a Launch Screen in SwiftUI

In this post we are going to look at how we can implement a launch screen in our SwiftUI project. In the past we would usually have to use a storyboard or XIB file to make our launch screens. In SwiftUI, we can now use the Info.plist to make our launch screen.

Let us get started by first navigating to our Info.plist file and towards the bottom we should see a “Launch Screen” area in our plist.

If we click the little plus button next to where it says “Dictionary” we should see a list of options popup.

  1. Background color: Here we can set the color of the launch screens background
  2. Image name: Here we can set an image to our launch screen at the images size / resolution
  3. Image respects safe area insets: This is a bool where we can allow the image to respect or exceed the safe area of the screen
  4. Show navigation bar: This is a bool where we can display a mock up of a Navigation bar
  5. Show Tab bar: This is a bool where we can display a mock up of a Tab bar
  6. Show Toolbar: This is a bool where we can display a mock up of a tool bar

In this example we are only going to add an image to our launch screen. To do this we will click on the “Image Name” option. This will add an image name property to our plist with a blank string. We will leave this blank for now but we will soon fill it in with our image name.

Next we will need to add an image to our Assets.xcassets file. Once we have dragged and dropped an image into our Assets.xcassets file, we will now copy the image name and paste it into the string area of “Launch Screen” “Image Name” back in our plist.

As you can see in the images above we added an image named “144” to our projects assets file. We then set that image in our Info.plist to be our launch screen image (Don’t ever name an image with a number 🀒). Now if we go and run our app we should see a quick glimpse of our launch screen image before the app loads.

That is all you need to make a launch screen in SwiftUI! This is just another example of how SwiftUI makes developers lives that much easier.

Hope this helps you on your next SwiftUI project!

Thanks for reading and Happy coding πŸš€πŸ“± πŸš€πŸ“±

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!