Autor: admin

  • Swift Package Manager Simplified

    Swift Package Manager Simplified

    The Swift Package Manager (SPM) helps developers modularize code, improve reusability, and streamline dependency management using Apple’s preferred tool. Many iOS developers are still transitioning from CocoaPods and Carthage, making a clear guide on creating and integrating SPM packages highly relevant. Additionally, SPM encourages open-source contributions, enhances team collaboration, and improves build times by promoting a more structured development approach.

    In this post, we will implement a simple SPM package that generates a random dice value. Later, we will integrate it into an iOS app that displays the dice value.

    Dice SPM

    The first step is to create and navigate into the folder that will contain the SPM package implementation. Use the following command to create the library scaffolding.

    swift package init --type library

    Open project with XCode.

    xed . 

    This is folder structure for the project:

    This is what it does our SPM:

    public struct DiceSPM {
        public static func roll() -> String {
            let values = ["Ace", "J", "K", "Q", "Red", "Black"]
            return values[Int.random(in: 0...(values.count - 1))]
        }
    }

    And its tests:

    @Test func example() async throws {
        var dicValues: [String: Int] = ["Ace": 0, "J": 0, "K": 0, "Q": 0, "Red": 0, "Black": 0]
        for _ in 0..<100 {
            let result: String = DiceSPM.roll()
            dicValues[result]! += 1
        }
        
        for value in dicValues.keys {
            #expect(dicValues[value] ?? 0 > 0)
        }
    }

    Build and run tests:

    Create an new GitHub public repository and upload all generated stuff:

    Last but not least, documenting the README.md file is always a good practice for regular source code, but for libraries (such as SPMs), it is a MUST.

    You can find SPM hosted in following GitHub repository.

    Dice Consumer

    DiceConsumer will be a simple app that retrieves values from the DiceSPM package. The first step is to import the SPM package.

    And just call SPM library implementation from View:

    import SwiftUI
    import DiceSPM
    
    struct ContentView: View {
        @State private var dice: String?
        var body: some View {
            VStack {
                if let dice = dice {
                    Text(dice)
                        .font(.largeTitle)
                }
                Button {
                    dice = DiceSPM.roll()
                } label: {
                    Text("Roll the dice!")
                }
    
            }
            .padding()
        }

    Finally build and deploy on simulator:

    Conclusions

    CocoaPods is no longer maintained, and Swift Package Manager (SPM) was intended to replace it and has now successfully succeeded it. In this post, I have demonstrated how easy it is to publish an SPM package and import it into any project.

    You can find source code used for writing this post in following repository

  • Breaking Retain Cycles in Swift

    Breaking Retain Cycles in Swift

    Detecting and preventing retain cycles is crucial, as they lead to memory leaks, degrade app performance, and cause unexpected behaviors. Many developers, especially those new to Swift and UIKit, struggle with understanding strong reference cycles in closures, delegates, and class relationships.

    We will present two classic retain cycle bugs in a sample iOS app, explore the tools that Xcode provides for detecting them, and share some advice on how to avoid them.

    Memory Graph Debuger

    The sample application consists of two view screens. The pushed screen contains injected retain cycles, leading to memory leaks. A memory leak occurs when memory references cannot be deallocated. In this app, the leak happens when the pushed screen is popped back but remains in memory.

    Build and deploy app on simulator (or real device): 

    Open Memory Graph Debuger

    In this case is clear where do we have a retain cycle.

    class MyViewModel: ObservableObject {
        @Published var count: Int = 0
        var classA: ClassA  = ClassA()
        
        var incrementClosure: (() -> Void)?
        
        init() {
    ...
            
            #if true
            incrementClosure = {
                self.count += 1
            }
            #else
    ...
            }
            #endif
        }
        
        deinit {
            print("MyViewModel is being deallocated")
        }
    }
    
    struct SecondView: View {
        @StateObject private var viewModel = MyViewModel()
        var body: some View {

    In SecondView, MyViewModel is referenced using viewModel, MyViewModel.incrementalClosure, and self, which also references MyViewModel indirectly. When the view is popped, this class cannot be removed from memory because it is retained due to an internal reference from self.count.

    If you set a breakpoint in the deinit method, you will notice that it is never triggered. This indicates that the class is still retained, leading to a memory leak. As a result, the memory allocated for MyViewModel will never be deallocated or reused, reducing the available memory for the app. When the app runs out of memory, iOS will forcefully terminate it.

    The only way to break this retain cycle is to make one of these references weak. Using a weak reference ensures that it is not counted toward the retain count. When the view is popped, SecondView holds the only strong reference, allowing iOS to deallocate MyViewModel and free up memory.

    This is the correct solution:

    class MyViewModel: ObservableObject {
        @Published var count: Int = 0
        var classA: ClassA  = ClassA()
        
        var incrementClosure: (() -> Void)?
        
        init() {
            ...
            
            #if false
          ....
            #else
            incrementClosure = { [weak self] in
                self?.count += 1
            }
            #endif
        }
        
        deinit {
            print("MyViewModel is being deallocated")
        }
    }

    Set a breakpoint in deinit to verify that the debugger stops when the view is popped. This confirms that the class has been properly deallocated

    Next retain cycle is a memory reference cycle, when we have a chain of refenced classes and once of them is referencing back it generates a loop of references. For implementing this memory leak we have created a classA that references a classB that references a classC that finally refences back to classA.

    Here we can see clear that same memory address is referenced. But if we take a look at Debug Memory Inspector

    It is not as clear as the previous case. This is a prepared sample app, but in a real-world application, the graph could become messy and make detecting memory leaks very difficult. Worst of all, with this kind of memory leak, when the view is removed, the deinit method is still being executed.

    For detecting such situations we will have to deal with another tool.

    Insruments

    Xcode Instruments is a powerful performance analysis and debugging tool provided by Apple for developers to profile and optimize their iOS, macOS, watchOS, and tvOS applications. It offers a suite of tools that allow developers to track memory usage, CPU performance, disk activity, network usage, and other system metrics in real-time. Instruments work by collecting data through time-based or event-based profiling, helping identify performance bottlenecks, memory leaks, and excessive resource consumption. Integrated within Xcode, it provides visual timelines, graphs, and detailed reports, making it an essential tool for fine-tuning app efficiency and responsiveness.

    In XCode Product menu select Profile:

    For measuring memory leaks select ‘Leaks»:

    Press record button for deploying on simulator and start recording traces.

    In following video, you will see that when view is pushed back then memory leak is detected:

    Is programed  to check memory every 10 seconds, when we click on red cross mark then bottom area shows the classes affected:

    Conclusions

    In this post, I have demonstrated how to detect memory leaks using the Memory Graph Debugger and Inspector. However, in my opinion, preventing memory leaks through good coding practices is even more important than detecting them.

    In Swift, memory leaks typically occur due to retain cycles, especially when using closures and strong references. To avoid memory leaks, you can use weak references where appropriate.

    You can find source code used for writing this post in following repository

    References

  • Boost Security: Enable Touch ID & Face ID

    Boost Security: Enable Touch ID & Face ID

    With the increasing reliance on biometric authentication for secure and seamless access, developers must understand how to integrate these features effectively. By breaking down the process, this post empowers developers to build more secure and user-friendly applications, aligning with Apple’s emphasis on privacy and cutting-edge technology.

    In this micro-post, you’ll see just how easy it is to implement biometric authentication on iOS.

    Authentication App

    Before start codign we need to fill in a message on ‘FaceIDUssageAuthentication:

    This is the view:

    struct ContentView: View {
        @State private var isAuthenticated = false
        @State private var errorMessage = ""
    
        var body: some View {
            VStack {
                if isAuthenticated {
                    Text("Authentication successful!")
                        .font(.title)
                        .foregroundColor(.green)
                } else {
                    Text(errorMessage)
                        .font(.title)
                        .foregroundColor(.red)
                }
    
                Button(action: {
                    authenticate()
                }) {
                    Text("Authenticate with Touch ID / Face ID")
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                }
            }
            .padding()
        }

    This code creates a simple SwiftUI view for handling biometric authentication. It displays a success or error message based on the authentication status and provides a button to trigger the authentication process. 

    And this is the authentication code:

        func authenticate() {
            let context = LAContext()
            var error: NSError?
    
            if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
                let reason = "Authenticate for having access to application"
    
                context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
                    DispatchQueue.main.async {
                        if success {
                            isAuthenticated = true
                            errorMessage = ""
                        } else {
                            isAuthenticated = false
                            errorMessage = "Failed authentication"
                        }
                    }
                }
            } else {
                isAuthenticated = false
                errorMessage = "Touch ID / Face ID no está disponible"
            }
        }

    The authenticate() function uses the Local Authentication framework to enable biometric authentication (Touch ID or Face ID) for accessing an application. It first checks if the device supports biometric authentication using canEvaluatePolicy. If supported, it prompts the user to authenticate with a reason message, and upon success, sets isAuthenticated to true and clears any error messages; if authentication fails, it sets isAuthenticated to false and updates errorMessage to indicate the failure. If biometric authentication is unavailable or not configured, it sets isAuthenticated to false and updates errorMessage to reflect that Touch ID/Face ID is not available. The function ensures UI updates are performed on the main thread, making it suitable for integration into apps requiring secure user access.

    Finally deploy in a real device:

    Conclusions

    As you can see in the code above, it is easy to integrate the same biometric authentication mechanism used to unlock the iPhone into your apps.

    You can find source code used for writing this post in following repository

    References

  • Boosting iOS App Flexibility with Firebase Remote Config

    Boosting iOS App Flexibility with Firebase Remote Config

    This post demonstrates how developers can dynamically update app behavior, UI elements, and features without requiring an App Store update. This capability is especially valuable for A/B testing, feature flagging, and personalized user experiences, making apps more adaptable and data-driven. Despite its benefits, many developers underutilize Remote Config. A step-by-step guide covering Firebase setup, SDK integration, fetching configurations, and best practices would offer significant value.

    In this post, we’ll walk through creating a sample iOS app that reads a feature flag and, based on its value, displays a different UI message.

    Setup Firebase and XCode

    In a previous post, Unlocking Firebase iOS Push Notifications, we explained how to set up a Firebase project for iOS from scratch. During this process, you obtained a file called GoogleService-Info.plist.

    You have to include it on your project, next step is include SPM Firebase Library.

    Add FirebaseCore and FirebaseRemoteConfig to your target.

    Create a Firebase Configuration Flag

    From your Firebase project side bar:

    Select ‘Remote Config’. And add a new parameter:

    In our implementation, ‘NewTentativeFeatureFlag’ will be a boolean (false) parameter. Once set, ensure that it is properly published.

    The iOS Remote Configuration App

    The Main ContentView retrieves the newTentativeFeatureFlag @Published attribute from the RemoteConfigManager component in Firebase:

    struct ContentView: View {
        @State private var showNewFeature = false
        @StateObject var remoteConfigManager = appSingletons.remoteConfigManager
        var body: some View {
            VStack {
                if remoteConfigManager.newTentativeFeatureFlag {
                    Text("New Feature is Enabled!")
                        .font(.largeTitle)
                        .foregroundColor(.green)
                } else {
                    Text("New Feature is Disabled.")
                        .font(.largeTitle)
                        .foregroundColor(.red)
                }
            }
        }
    }

    Depending on the value obtained, a different text is printed with a different color. This is a very simplistic example, but it could represent an A/B test, a new feature, or any functionality you want to run live.

    An alternative valid implementation could be to call getBoolValue inside the .onAppear modifier instead of using the @published attribute from RemoteConfigManager.

    RemoteConfigManager is the component that wraps Firebase Remote Config functionality.

    import Foundation
    import Firebase
    
    @globalActor
    actor GlobalManager {
        static var shared = GlobalManager()
    }
    
    @GlobalManager
    class RemoteConfigManager: ObservableObject {
        @MainActor
        @Published var newTentativeFeatureFlag: Bool = false
        
        private var internalNewTentativeFeatureFlag = false {
            didSet {
                Task { @MainActor [internalNewTentativeFeatureFlag]  in
                    newTentativeFeatureFlag = internalNewTentativeFeatureFlag
                }
            }
        }
        
        private var remoteConfig: RemoteConfig =  RemoteConfig.remoteConfig()
        private var configured = false
    
        @MainActor
        init() {
            Task { @GlobalManager in
                await self.setupRemoteConfig()
            }
        }
        
        private func setupRemoteConfig() async {
            guard !configured else { return }
            
            let settings = RemoteConfigSettings()
            settings.minimumFetchInterval = 0
            remoteConfig.configSettings = settings
            
            fetchConfig { [weak self] result in
                guard let self else { return }
                Task { @GlobalManager [result] in
                    configured = result
                    self.internalNewTentativeFeatureFlag = self.getBoolValue(forKey: "NewTentativeFeatureFlag")
                }
            }
        }
    
        private func fetchConfig(completion: @escaping @Sendable (Bool) -> Void) {
            remoteConfig.fetch { status, error in
                if status == .success {
                    Task { @GlobalManager in
                        self.remoteConfig.activate { changed, error in
                            completion(true)
                        }
                    }
                } else {
                    completion(false)
                }
            }
        }
        
        func getBoolValue(forKey key: String) -> Bool {
            return remoteConfig[key].boolValue
        }
        
        func getStringValue(forKey key: String) -> String {
            return remoteConfig[key].stringValue
        }
    }

    The code is already compatible with Swift 6 and defines a RemoteConfigManager class responsible for fetching and managing Firebase Remote Config values in a SwiftUI application. To ensure thread safety, all operations related to Remote Config are handled within a global actor (GlobalManager).

    The RemoteConfigManager class conforms to ObservableObject, allowing SwiftUI views to react to changes in its properties. The newTentativeFeatureFlag property is marked with @Published and updated safely on the main actor to maintain UI responsiveness.

    The class initializes Remote Config settings, fetches values asynchronously, and updates internalNewTentativeFeatureFlag accordingly. This design ensures efficient Remote Config value retrieval while maintaining proper concurrency handling in a Swift application.

    Build and run

    As title suggests, build and run:

    In Firebase Remote Config, ‘NewTentativeFeatureFlag’ is set to true, and the view is displaying the correct message. Now, let’s switch the value to false and restart the application. Yes, I said restart, because when the value is changed in the console, Firebase Remote Config has no mechanism to notify the app. The app must periodically fetch the value to detect any changes in its state.

    Now turn ‘NewTentativeFeatureFlag’  to false and re-start the app.

    Conclusions

    Firebase Remote Config is essential for implementing A/B tests and serves as a great mechanism for disabling immature functionalities that might fail in production (e.g., a new payment method).

    You can find source code used for writing this post in following repository

    References

  • Boost Your iOS Development with Preprocessing Directives

    Boost Your iOS Development with Preprocessing Directives

    Preprocessor directives such as #if, #else, #endif, and #define are powerful tools in Objective-C and Swift. They enable developers to conditionally compile code, manage different build configurations, and optimize apps for various platforms or environments. Understanding these concepts helps streamline code, improve debugging, and create more flexible, maintainable projects.
    In the following post, I will present code snippets that demonstrate the use of preprocessing directives. I hope you find them useful!

    Preprocessing directives

    Preprocessing directives in Swift are instructions that are interpreted by the Swift compiler before the actual compilation of the code begins. These directives allow developers to include or exclude portions of code based on certain conditions, such as the target operating system, compiler flags, or custom-defined conditions. Common preprocessing directives in Swift include #if#elseif#else, and #endif, which are used for conditional compilation. For example, you can use these directives to write platform-specific code, ensuring that only the relevant code for a particular platform (like iOS or macOS) is compiled. This helps in maintaining a single codebase for multiple platforms while still accommodating platform-specific requirements.

    The concept of preprocessing directives originates from the C programming language, where the C preprocessor (cpp) is used to manipulate the source code before it is compiled. Swift, being influenced by C and Objective-C, adopted a similar mechanism but with some differences. Unlike C, Swift does not have a separate preprocessor; instead, these directives are handled directly by the Swift compiler. This integration simplifies the build process and avoids some of the complexities and pitfalls associated with traditional preprocessors. The use of preprocessing directives in Swift reflects the language’s goal of providing modern, safe, and efficient tools for developers while maintaining compatibility with existing practices from its predecessor languages.

    #if, #elsif, #else and #endif

    Platform-Specific Code

    You can use #if to write code that compiles only for specific platforms, such as iOS, macOS, or Linux. This is useful for handling platform-specific APIs or behavior.

    #if os(iOS)
        print("Running on iOS")
    #elseif os(macOS)
        print("Running on macOS")
    #elseif os(Linux)
        print("Running on Linux")
    #else
        print("Running on an unknown platform")
    #endif

    Custom Compiler Flags

    Also you can define custom compiler flags in your build settings and use them to conditionally compile code. For example, you might want to include debug-only code or feature toggles.

    #if DEBUG
        print("Debug mode is enabled")
    #elseif RELEASE
        print("Release mode is enabled")
    #else
        print("Unknown build configuration")
    #endif

    Feature Toggles

    Use conditional compilation to enable or disable features based on custom conditions.

            #if EXPERIMENTAL_FEATURE
                print("Experimental feature is enabled")
            #else
                print("Experimental feature is disabled")
            #endif
     

    Open the target settings and add -DEXPERIMENTAL_FEATURE on Other Swift Flags

    Checking Swift Version

    You can use conditional compilation to check the Swift version being used.

    #if swift(>=5.0)
        print("Using Swift 5.0 or later")
    #else
        print("Using an older version of Swift")
    #endif
     

    #available

    The #available directive in Swift is used to check the availability of APIs at runtime based on the operating system version or platform. This is particularly useful when you want to use newer APIs while maintaining compatibility with older versions of the operating system.

    Purpose of #available is ensure that your app does not crash when running on older versions of the operating system that do not support certain APIs. Also it allows you to provide fallback behavior for older OS versions.

    if #available(iOS 15, macOS 12.0, *) {
        // Use APIs available on iOS 15 and macOS 12.0 or later
        let sharedFeature = SharedFeatureClass()
        sharedFeature.doSomething()
    } else {
        // Fallback for older versions
        print("This feature requires iOS 15 or macOS 12.0.")
    }

    If your code runs on multiple platforms (e.g., iOS and macOS), you can check availability for each platform.

    #warning and #error:

    The #warning and #error directives in Swift are used to emit custom warnings or errors during compilation. These are helpful for:

    1. Marking incomplete or problematic code.

    2. Enforcing coding standards or requirements.

    3. Providing reminders for future work.

    4. Preventing compilation if certain conditions are not met.

    Unlike runtime warnings or errors, these directives are evaluated at compile time, meaning they can catch issues before the code is even run.

    The #warning directive generates a compile-time warning. It does not stop the compilation process but alerts the developer to potential issues or tasks that need attention.

    func fetchData() {
        #warning("Replace with network call once API is ready")
        let data = mockData()
    }

    The #error directive generates a compile-time error. It stops the compilation process entirely, ensuring that the code cannot be built until the issue is resolved.

    func newFeature() {
        #error("This feature is not yet implemented.")
    }

    Conclusions

    In this post, I have provide you a few preprocessiong directives that I have considered most usefull. You can find source code used for writing this post in following repository

  • Unlocking Firebase iOS Push Notifications

    Unlocking Firebase iOS Push Notifications

    This post covers setting up and running push notifications, addressing a common yet often confusing aspect of app development. Many developers, especially beginners, struggle with configuring Apple Push Notification Service (APNs), handling authentication keys, and managing payloads. A well-structured guide can simplify these steps, offer troubleshooting insights, and help developers avoid common pitfalls.

    Push notifications are crucial for user engagement, making it essential to implement them effectively. This tutorial aims to provide a clear, step-by-step approach to help developers integrate push notifications, ultimately improving app retention and user experience.

    In this post, we will set up push notifications using Firebase and implement a basic iOS app that receives them.

    The blank iOS Push Notifications ready app project

    Create a blank project:

    I stop at this point just to notice de ‘Bundle Identifier’ because we will nee it further on. Open target settings:

    Add Push Notifications and Background Modes:

    And check ‘Remote notifications:

    Generating keys on Apple Developer portal

    For generating keys, it is mandatory to have an Apple Developer Account (or higher-tier subscriptions). Go to Certificates, Identifiers & Profiles section

    Add a new key (+). Fill in a key name:

    And check ‘Apple Push Notifications service (APNs).

    Continue

    Important: Two things to note: keep track of the Key ID and download the .p8 key; you will need both later. And last but not least:

    Take note of your Team ID by visiting your Apple Developer Account. For the next step, you will need the following:

    • App Bundle ID
    • .p8 key file
    • Key ID
    • Team ID

    Firebase

    To continue, you will need a Firebase account and create a new project.

    Fulfill Google Analytics account and location:

    Setup iOS app Configuration

    Time to fill iOS App bundle:

    Next step will present us SPM GitHub url:

    Add SPM package in XCode:

    Add FirebaseMessaging to your target:

    In this case, since we are only using Firebase’s Push Notification service, we only need FirebaseCore as a base and FirebaseMessaging itself. The final step involves the Firebase wizard providing the code to start working with the iOS app.

    During this process, you will be provided with the GoogleService-Info.plist file. Keep it, as you will need to incorporate it into your iOS app’s source code.

    iOS app ready to receive pushes

    Add the GoogleService-Info.plist configuration file generated in the previous Firebase configuration step. For security reasons, the GoogleService-Info.plist file will not be uploaded to the GitHub repository.

    This is AppDelegate implementation:

    import SwiftUI
    import FirebaseCore
    import UserNotifications
    import FirebaseMessaging
    
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            FirebaseApp.configure()
            
            UNUserNotificationCenter.current().delegate = self
            Messaging.messaging().delegate = self
            
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
                if granted {
                    print("Graned permission for receiving notifications")
                    DispatchQueue.main.async {
                        UIApplication.shared.registerForRemoteNotifications()
                    }
                } else {
                    print("Permision denied for receiving notifications")
                }
            }
            
            return true
        }
        
        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
            let token = tokenParts.joined()
            print("APNs Token: \(token)")
    
            Messaging.messaging().apnsToken = deviceToken
        }
        
        func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
            if let fcmToken = fcmToken {
                print("FCM Token: \(fcmToken)")
            }
        }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler([.banner, .sound])
        }
        
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
            completionHandler()
        }
    }
    
    @main
    struct PushNotificationsSampleApp: App {
        @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
      }

    This SwiftUI code configures an iOS app to handle push notifications using Firebase Cloud Messaging (FCM). It initializes Firebase, requests user permission for notifications, and registers the app with Apple Push Notification service (APNs) to receive device tokens. The AppDelegate class handles FCM token updates, displays notifications when the app is in the foreground, and manages user interactions with those notifications. The app’s main entry point links the AppDelegate to the SwiftUI lifecycle and sets up the initial view. This setup enables the app to receive and display push notifications, making it suitable for use cases such as messaging, social media, or e-commerce apps.

    When building the app for the first time, the user will be prompted to allow notifications.

    Please say Allow, if all was setup ok in the logs you will find FCM token printed:

    The FCM token (Firebase Cloud Messaging token) is a unique identifier assigned by Firebase to each device instance of your app. It is used to reliably deliver push notifications to specific devices. Be sure to keep track of this value, as you’ll need it later.

    Send Push Notification

    Now it’s time to check if everything was set up correctly by sending a push notification. Go back to the Firebase Console.

    Open project settings menu option and select Messaging tab.

    Upload the .p8 key file generated from the Apple Developer portal, along with the Key ID and Team ID values. Then, navigate to the ‘Messaging’ sidebar option.

    Fill in notification title and text and press send message:

    Fill in notification title and text and press send message:

    Finally paste FCM token that you got from XCode log, press Test and:

    Voila! here you go!

    Conclusions

    Setting up push notifications is typically a one-time implementation with minimal ongoing maintenance. However, it’s easy to make mistakes. The intention of this post is to present a simple way to set up push notifications if you’ve never encountered them before.

    You can find the source code used for this post in the repository linked below.

    References

  • Real-Time Speed Limit Detection in iOS Using Vision

    Real-Time Speed Limit Detection in iOS Using Vision

    iOS development focused on detecting text in a video recording scene using Vision and AVFoundation is incredibly valuable for developers interested in building apps with real-time image processing or OCR capabilities. This post provides hands-on guidance on how to combine AVFoundation’s video capture features with Vision’s powerful text recognition capabilities, allowing developers to create apps that automatically extract and analyze text from videos. It is especially useful for building innovative apps in fields such as accessibility, document scanning, or interactive media, offering both technical insights and practical code examples to help developers implement advanced text detection in their projects.

    In this post, we will walk through creating a sample iOS app that detects speed limit traffic signs. At the end of the post, you will find a GitHub repository link to the source code.

    iOS Speed signal detection app

    The app basically detects and filter those ones that could fit with a speed limit:

    The View

    Main ContentView retrieves possible speed detection text and just prints a speed limit traffic signal with detected speed value on it:

    struct ContentView: View {
        @State private var detectedSpeed: String = ""
        var body: some View {
            ZStack {
                CameraView(detectedSpeed: $detectedSpeed)
                    .edgesIgnoringSafeArea(.all)
                
                trafficLimitSpeedSignalView(detectedSpeed)
            }
        }
        
        func trafficLimitSpeedSignalView(_ detectedText: String ) -> some View {
            if !detectedText.isEmpty {
                return AnyView(
                ZStack {
                     Circle()
                         .stroke(Color.red, lineWidth: 15)
                         .frame(width: 150, height: 150)
                     Circle()
                         .fill(Color.white)
                         .frame(width: 140, height: 140)
                     
                     Text("\(detectedText)")
                         .font(.system(size: 80, weight: .heavy))
                         .foregroundColor(.black)
                 }
                )
            } else {
                return AnyView(EmptyView())
            }
        }
    }

    CameraView, where all magic takes place…

    Key library frameworks have been the following:

    • AVCaptureSession: Captures video data from the device camera.
    • VNRecognizeTextRequest: Part of Apple’s Vision framework used for Optical Character Recognition (OCR) to recognize text in images.
     
    This code defines a SwiftUI CameraView component that uses the device’s camera to capture video, and processes the video feed to detect and extract speed values from any visible text (e.g., road signs with speed limits).
    struct CameraView: UIViewControllerRepresentable {
        @Binding var detectedSpeed: String
    • UIViewControllerRepresentable structure integrates a UIViewController (specifically a camera view) into a SwiftUI-based application. SwiftUI is future, but not for this applications context yet.
    • @Binding var detectedSpeed: String: A binding to a string that will hold the detected speed from the camera feed. Changes on this property wraper will update main ContentView.
       func makeCoordinator() -> Coordinator {
            return Coordinator(detectedSpeed: $detectedSpeed)
        }
    
        func makeUIViewController(context: Context) -> UIViewController {
            let controller = UIViewController()
            let captureSession = AVCaptureSession()
            captureSession.sessionPreset = .high
    
            guard let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
                let videoInput = try? AVCaptureDeviceInput(device: videoDevice) else {
                return controller
            }
            captureSession.addInput(videoInput)
    
            let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer.videoGravity = .resizeAspectFill
            previewLayer.frame = controller.view.layer.bounds
            controller.view.layer.addSublayer(previewLayer)
    
            let videoOutput = AVCaptureVideoDataOutput()
            videoOutput.setSampleBufferDelegate(context.coordinator, queue: DispatchQueue(label: "videoQueue"))
            captureSession.addOutput(videoOutput)
    
            Task { @GlobalManager in
                captureSession.startRunning()
            }
    
            return controller
        }
    
        func updateUIViewController(_ uiViewController: UIViewController, context: Context) { }

    Next, Methods in CameraView:

    • makeCoordinator(): Creates an instance of the Coordinator class that manages the camera’s data output and processes the video feed.

    • makeUIViewController(context:): This method sets up and configures the camera session:

      • AVCaptureSession: A session to manage the input from the camera and output to process the captured video.
      • AVCaptureDevice: Selects the device’s rear camera (.back).
      • AVCaptureDeviceInput: Creates an input from the rear camera.
      • AVCaptureVideoPreviewLayer: Displays a live preview of the video feed on the screen.
      • AVCaptureVideoDataOutput: Captures video frames for processing by the Coordinator class.
      • captureSession.startRunning(): Starts the video capture.
    • updateUIViewController(_, context:): This method is required by the UIViewControllerRepresentable protocol but is left empty in this case because no updates to the view controller are needed after initial setup.

    class Coordinator: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
    
            @Binding var detectedSpeed: String
    
            init(detectedSpeed: Binding<String>) {
                _detectedSpeed = detectedSpeed
            }
    
            func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
                guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
                recognizeText(in: pixelBuffer)
            }
    
            private func recognizeText(in image: CVPixelBuffer) {
                let textRequest = VNRecognizeTextRequest { [weak self] (request, error) in
                    guard let self,
                        let observations = request.results as? [VNRecognizedTextObservation],
                        let topCandidate = self.getCandidate(from: observations) else {
                        return
                    }
                    if let speedCandidate = Int(topCandidate),
                        (10...130).contains(speedCandidate),
                        speedCandidate % 10 == 0 {
                        print("Speed candidate: \(speedCandidate)")
                        detectedSpeed = "\(speedCandidate)"
                    }
                }
    
                let requestHandler = VNImageRequestHandler(cvPixelBuffer: image, options: [:])
                try? requestHandler.perform([textRequest])
            }
    
            private func getCandidate(from observations: [VNRecognizedTextObservation]) -> String? {
                var candidates = [String]()
                for observation in observations {
                    for candidate in observation.topCandidates(10) {
                        if candidate.confidence > 0.9,
                            let speedCandidate = Int(candidate.string),
                            (10...130).contains(speedCandidate),
                            speedCandidate % 10 == 0 {
                            candidates.append(candidate.string)
                        }
                    }
                }
                return candidates.firstMostCommonItemRepeated()
            }
        }

    Coordinator class is responsible for handling the video feed and extracting relevant text (i.e., speed values) from the camera image.

    • Properties:
      • @Binding var detectedSpeed: String: A binding to update the detected speed from the camera feed.
    • Methods:
      1. captureOutput(_:didOutput:from:): This delegate method is called whenever a new video frame is captured. It gets the pixel buffer from the frame and passes it to the recognizeText(in:) method to detect text.

      2. recognizeText(in:): This method uses Vision framework (VNRecognizeTextRequest) to perform text recognition on the captured video frame. The recognized text is checked to see if it contains a valid speed value (a number between 10 and 130, divisible by 10).

        • If a valid speed is detected, it updates the detectedSpeed binding to show the recognized speed.
      3. getCandidate(from:): This method processes multiple recognized text candidates and selects the most likely speed value based on:

        • High confidence (over 90%).
        • Speed range (10 to 130, divisible by 10).
        • Returning the most common speed value if multiple candidates are found.

    Conclusions

    This example dips our feet in the huge broad posibilites that will bring Vision Framework, not only limited to text detection but shapes also are possible.

    You can find source code used for writing this post in following repository. Also can play with this implementation in an app called Car Clip Camera placed at Apple Store.

    References

  • The MVVM-C Blueprint for iOS Apps

    The MVVM-C Blueprint for iOS Apps

    The MVVM-C pattern, which combines the Model-View-ViewModel (MVVM) architecture with a Coordinator layer, offers a structured approach to building scalable and maintainable iOS apps. It effectively separates concerns, making the codebase more modular and easier to test.

    In this tutorial, we will implement a sample focused solely on its navigation components. At the end of the post, you will find the GitHub repository where you can access the sample project used for this tutorial.

    The coordinator component

    In the MVVM-C (Model-View-ViewModel-Coordinator) pattern, the Coordinator is responsible for managing navigation and application flow, ensuring that the View and ViewModel remain focused on UI presentation and business logic, respectively, without being concerned with navigation and flow management. It handles the creation and configuration of View and ViewModel instances, determines which screen to display next based on user actions or app logic, and manages transitions between screens. By centralizing navigation logic, the Coordinator promotes modularity, reusability, and testability, maintaining a clean and scalable architecture.

    Depending on the complexity of the app, the Coordinator can be implemented in different ways:

    • Whole App Coordinator – Best for small apps with a few screens, where a single component can effectively manage the navigation flow.
    • Flow Coordinator – In larger apps, a single coordinator becomes difficult to manage. Grouping screens by business flow improves modularity and maintainability.
    • Screen Coordinator – Each screen has its own dedicated coordinator, making it useful for reusable components, such as a payment screen appearing in different user journeys. This approach is often used in architectures like VIPER, where each module operates independently.

    Ultimately, the choice of implementation depends on the app’s complexity and business requirements; no single pattern fits all use cases.

    The sample app

    The app we are going to implement is a Tab View app. Each tab represents a different navigation flow:

    flowtab1
    Screenshot

    The First Tab Flow is a flow coordinator that presents a Primary View with two buttons. These buttons navigate to either Secondary View 1 or Secondary View 2.

    • When Secondary View 2 appears, it includes a button that allows navigation to Tertiary View 1.
    • In Tertiary View 1, there is a button that returns directly to the Primary View or allows navigation back to the previous screen using the back button.
    • Secondary View 2 does not lead to any additional views; users can only return to the previous screen using the back button.

    The Second Tab Flow is managed by a Screen Coordinator, which presents a single screen with a button that opens a view model.

    • In this context, we consider the modal to be part of the view.
    • However, depending on the app’s design, the modal might instead be managed by the coordinator.

    Main Tab View

    This is the entry view point from the app:

    struct MainView: View {
        @StateObject private var tab1Coordinator = Tab1Coordinator()
        @StateObject private var tab2Coordinator = Tab2Coordinator()
    
        var body: some View {
            TabView {
                NavigationStack(path: $tab1Coordinator.path) {
                    tab1Coordinator.build(page: .primary)
                        .navigationDestination(for: Tab1Page.self) { page in
                            tab1Coordinator.build(page: page)
                        }
                }
                .tabItem {
                    Label("Tab 1", systemImage: "1.circle")
                }
    
                NavigationStack(path: $tab2Coordinator.path) {
                    tab2Coordinator.build(page: .primary)
                        .navigationDestination(for: Tab2Page.self) { page in
                            tab2Coordinator.build(page: page)
                        }
                }
                .tabItem {
                    Label("Tab 2", systemImage: "2.circle")
                }
            }
        }
    }

    The provided SwiftUI code defines a MainView with a TabView containing two tabs, each managed by its own coordinator (Tab1Coordinator and Tab2Coordinator). Each tab uses a NavigationStack bound to the coordinator’s path property to handle navigation. The coordinator’s build(page:) method constructs the appropriate views for both the root (.primary) and subsequent pages.

    The navigationDestination(for:) modifier ensures dynamic view creation based on the navigation stack, while the tabItem modifier sets the label and icon for each tab. This structure effectively decouples navigation logic from the view hierarchy, promoting modularity and ease of maintenance.

    Another key aspect is selecting an appropriate folder structure. The one I have chosen is as follows:

    Screenshot

    This may not be the best method, but it follows a protocol to prevent getting lost when searching for files.

    The flow coordinator

    The first structure we need to create is an enum that defines the screens included in the flow:

    enum Tab1Page: Hashable {
        case primary
        case secondary1
        case secondary2
        case tertiary
    }

    Hashable is not free; we need to push and pop those cases into a NavigationPath. The body of the coordinator is as follows:

    class Tab1Coordinator: ObservableObject {
        @Published var path = NavigationPath()
    
        func push(_ page: Tab1Page) {
            path.append(page)
        }
    
        func pop() {
            path.removeLast()
        }
    
        func popToRoot() {
            path.removeLast(path.count)
        }
    
        @ViewBuilder
           func build(page: Tab1Page) -> some View {
               switch page {
               case .primary:
                   Tab1PrimaryView(coordinator: self)
               case .secondary1:
                   Tab1SecondaryView1(coordinator: self)
               case .secondary2:
                   Tab1SecondaryView2()
               case .tertiary:
                   Tab1TertiaryView(coordinator: self)
               }
           }
    }

    The Tab1Coordinator class is an ObservableObject that manages navigation within a SwiftUI view hierarchy for a specific tab (Tab1). It uses a NavigationPath to track the navigation stack, allowing views to be pushed onto or popped from the stack through methods such as push(_:), pop(), and popToRoot(). The @Published property path ensures that any changes to the navigation stack are automatically reflected in the UI.

    The build(page:) method, marked with @ViewBuilder, constructs and returns the appropriate SwiftUI view (e.g., Tab1PrimaryView, Tab1SecondaryView1, Tab1SecondaryView2, or Tab1TertiaryView) based on the provided Tab1Page enum case. This approach enables dynamic navigation between views while maintaining a clean separation of concerns.

    The last section of the coordinator is the protocol implementation for the views presented by the coordinator. When a view has completed its work, it delegates the decision of which screen to present next to the coordinator. The coordinator is responsible for managing the navigation logic, not the view.

    extension Tab1Coordinator: Tab1PrimaryViewProtocol {
        func goToSecondary1() {
            push(.secondary1)
        }
        func goToSecondary2() {
            push(.secondary2)
        }
    }
    
    extension Tab1Coordinator: Tab1SecondaryView1Protocol {
        func goToTertiaryView() {
            push(.tertiary)
        }
    }
    
    extension Tab1Coordinator: Tab1TertiaryViewProtocol {
        func backToRoot() {
            self.popToRoot()
        }
    }
    

    This is the code from one of the views:

    import SwiftUI
    
    protocol Tab1PrimaryViewProtocol: AnyObject {
        func goToSecondary1()
        func goToSecondary2()
    }
    
    struct Tab1PrimaryView: View {
         let coordinator: Tab1PrimaryViewProtocol
        
            var body: some View {
                
                VStack {
                    Button("Go to Secondary 1") {
                        coordinator.goToSecondary1()
                    }
                    .padding()
    
                    Button("Go to Secondary 2") {
                        coordinator.goToSecondary2()
                    }
                    .padding()
                }
                .navigationTitle("Primary View")
            }
    }

    When the view doesn’t know how to proceed, it should call its delegate (the Coordinator) to continue.

    The screen coordinator

    The first structure we need to create is an enum that defines the screens in the flow:

    enum Tab2Page: Hashable {
        case primary
    }
    
    class Tab2Coordinator: ObservableObject {
        @Published var path = NavigationPath()
        
        @ViewBuilder
        func build(page: Tab2Page) -> some View {
            switch page {
            case .primary:
                Tab2PrimaryView(coordinator: self)
            }
        }
    }

    Hashable is not free; we need to push/pop these cases into a NavigationPath. The body of the coordinator is simply as follows:

    class Tab1Coordinator: ObservableObject {
        @Published var path = NavigationPath()
    
        func push(_ page: Tab1Page) {
            path.append(page)
        }
    
        func pop() {
            path.removeLast()
        }
    
        func popToRoot() {
            path.removeLast(path.count)
        }
    
        @ViewBuilder
           func build(page: Tab1Page) -> some View {
               switch page {
               case .primary:
                   Tab1PrimaryView(coordinator: self)
               case .secondary1:
                   Tab1SecondaryView1(coordinator: self)
               case .secondary2:
                   Tab1SecondaryView2()
               case .tertiary:
                   Tab1TertiaryView(coordinator: self)
               }
           }
    }

    The provided code defines a SwiftUI-based navigation structure for a tabbed interface. The Tab2Coordinator class is an ObservableObject that manages the navigation state using a NavigationPath, which is a state container for navigation in SwiftUI. The @Published property path allows the view to observe and react to changes in the navigation stack. The build(page:) method is a ViewBuilder that constructs the appropriate view based on the Tab2Page enum case. Specifically, when the page is .primary, it creates and returns a Tab2PrimaryView, passing the coordinator itself as a dependency.

    This approach is commonly used in SwiftUI apps to handle navigation between different views within a tab, promoting a clean separation of concerns and state management. The Tab2Page enum is marked as Hashable, which is required for it to work with NavigationPath.

    Conclusions

    Coordinator is a key component that allows to unload ViewModel or ViewModel logic for controlling navigation logic. I hope this post will help you to understand better this pattern.

    You can find the source code used for this post in the repository linked below.

    References

  • WebSockets Made Easy: Create a Simple Chat App in iOS

    WebSockets Made Easy: Create a Simple Chat App in iOS

    In this post, I will highlight how WebSockets enable real-time communication with minimal complexity. By leveraging WebSockets, developers can implement instant message delivery without relying on complex polling or delayed responses. This is crucial for providing a smooth user experience in chat applications. With iOS’s native support for WebSockets—such as URLSessionWebSocketTask—this post will demonstrate a simple, modern, and efficient solution for real-time messaging, while teaching developers essential skills like asynchronous communication and network management.

    In this tutorial, we will create a server using a Dockerized Node.js environment and two client applications: a simple HTML-JavaScript client and an iOS app WebSocket client.

    Websocket chat server

    To avoid confusion, let’s create a server folder to store all the necessary files. The first step is to create a new, blank Node.js project

    npm init -y
    Next setup library dependencies required.
    npm install ws express cors
    The libraries ws, express, and cors are installed on the server-side to provide essential functionalities for a modern web application. The ‘ws’ library enables WebSocket implementation in Node.js, allowing real-time bidirectional communication between clients and the server, which is crucial for chat applications. Express is a web application framework for Node.js that simplifies the creation of HTTP servers and route handling, making it easier to set up and manage the web application. Lastly, the ‘cors’ library is used to enable Cross-Origin Resource Sharing (CORS), a security mechanism that controls access to resources from different domains, ensuring that the server can safely interact with clients from various origins. Together, these libraries create a robust server capable of handling WebSocket connections, efficient HTTP routing, and secure cross-origin resource sharing.
    ‘server.js’ will contain our server code:
    const WebSocket = require('ws');
    const express = require('express');
    const cors = require('cors');
    
    const app = express();
    app.use(cors());
    
    const server = app.listen(8080, () => {
      console.log('Servidor HTTP escuchando en el puerto 8080');
    });
    
    const wss = new WebSocket.Server({ server });
    
    wss.on('connection', (ws) => {
      console.log('Cliente conectado');
    
      ws.on('message', (message) => {
        console.log(`Mensaje recibido: ${message}`);
        
        // Enviar el mensaje a todos los clientes conectados
        wss.clients.forEach((client) => {
          if (client.readyState === WebSocket.OPEN) {
            client.send(message.toString());
          }
        });
      });
    
      ws.on('close', () => {
        console.log('Cliente desconectado');
      });
    });
    
    This code sets up a WebSocket server integrated with an Express HTTP server running on port 8080. It allows real-time communication between the server and connected WebSocket clients. The server uses CORS middleware to handle cross-origin requests. When a client connects to the WebSocket server, a connection event is logged. The server listens for messages from the client, logs received messages, and broadcasts them to all connected clients that have an open WebSocket connection. It also logs when a client disconnects. This code facilitates bidirectional, real-time message distribution among multiple WebSocket clients.
    Lets dockerize the server, create ‘Dockerfile’:
    FROM node:14
    WORKDIR /usr/src/app
    COPY package*.json ./
    RUN npm install
    COPY . .
    EXPOSE 8080
    CMD ["node", "server.js"]
    This Dockerfile sets up a containerized environment for a Node.js application using the Node.js 14 image. It configures the working directory, copies application files and dependencies, installs the required Node.js packages, exposes port 8080 for the application, and specifies that server.js should run using Node.js when the container starts.
    Now is time to create docker image:
    docker build -t websocket-chat-server .

    Finally run the image:

    docker run -p 8080:8080 -d websocket-chat-server
    Screenshot

    For validating websocket server we will create an small html-javascript client:

    <!DOCTYPE html>
    <html>
    <body>
      <ul id="messages"></ul>
      <input type="text" id="messageInput" placeholder="Write a message">
      <button onclick="sendMessage()">Send</button>
    
      <script>
        const socket = new WebSocket('ws://localhost:8080');
    
        socket.onopen = function(event) {
          console.log('Setup connection', event);
        };
    
        socket.onmessage = function(event) {
          const messages = document.getElementById('messages');
          const li = document.createElement('li');
          li.textContent = event.data;
          messages.appendChild(li);
        };
    
        function sendMessage() {
          const input = document.getElementById('messageInput');
          const message = input.value;
          socket.send(message);
          input.value = '';
        }
      </script>
    </body>
    </html>

    This HTML code creates a basic web-based chat interface using WebSocket for real-time communication. It consists of an unordered list (<ul>) to display messages, an input field (<input>) for entering messages, and a «Send» button. The script establishes a WebSocket connection to a server at ws://localhost:8080. When the connection opens, a log message is displayed in the console. Incoming messages from the WebSocket server are dynamically added as list items (<li>) to the message list. When the «Send» button is clicked, the sendMessage function retrieves the user’s input, sends it to the server via the WebSocket, and clears the input field.

    Open file with your favourite browser:

    Screenshot

    Console log show that is properly connected and messages written are properly broadcasted

    websocket iOS Client

    We will follow the same design as we did with HTML and JavaScript:

    struct ContentView: View {
        @StateObject private var webSocketManager = WebSocketManager()
        @State private var messageText = ""
        
        var body: some View {
            VStack {
                List(webSocketManager.messages, id: \.self) { message in
                    Text(message)
                }
                
                HStack {
                    TextField("Enter message", text: $messageText)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    
                    Button("Send") {
                        webSocketManager.send(messageText)
                        messageText = ""
                    }
                }.padding()
            }
            .onAppear {
                webSocketManager.connect()
            }
        }
    }
    Code defines a ContentView that interacts with a WebSocket connection to display and send messages in a real-time chat interface. It uses a WebSocketManager (assumed to handle WebSocket connections and messaging) as a @StateObject, ensuring it persists across view updates. The body consists of a VStack with a List that dynamically displays messages received via the WebSocket, and an input section with a TextField for composing messages and a Button to send them. When the button is pressed, the typed message is sent via the webSocketManager, and the input field is cleared. The onAppear modifier ensures that the WebSocket connection is initiated when the view appears on screen.
    Finally WebSocketManager is where all magic takes place:
    class WebSocketManager: ObservableObject {
        private var webSocketTask: URLSessionWebSocketTask?
        @Published var messages: [String] = []
        
        func connect() {
            let url = URL(string: "ws://localhost:8080")!
            webSocketTask = URLSession.shared.webSocketTask(with: url)
            webSocketTask?.resume()
            receiveMessage()
        }
        
        func send(_ message: String) {
            webSocketTask?.send(.string(message)) { error in
                if let error = error {
                    print("Error sending message: \(error)")
                }
            }
        }
        
        private func receiveMessage() {
            webSocketTask?.receive { result in
                switch result {
                case .failure(let error):
                    print("Error receiving message: \(error)")
                case .success(let message):
                    switch message {
                    case .string(let text):
                        DispatchQueue.main.async {
                            self.messages.append(text)
                        }
                    default:
                        break
                    }
                    self.receiveMessage()
                }
            }
        }
    }
    The WebSocketManager class manages a WebSocket connection and handles sending and receiving messages. It uses URLSessionWebSocketTask to connect to a WebSocket server at a specified URL (ws://localhost:8080) and maintains an observable array of received messages, messages, for use in SwiftUI or other reactive contexts. The connect method establishes the connection and starts listening for incoming messages using the private receiveMessage method, which recursively listens for new messages and appends them to the messages array on the main thread. The send method allows sending a string message over the WebSocket, with error handling for failures. This class encapsulates WebSocket communication in a way that supports reactive UI updates.
    Finally, place both front ends (iPhone and web client) side by side. If you followed the instructions, you should have a chat between them.

    Conclusions

    WebSocket is a server technology, distinct from REST APIs or GraphQL, that is particularly well-suited for real-time, bidirectional communication. It’s ideal for applications that require fast, continuous interactions, such as real-time chats, online games, and collaborative tools (e.g., Figma, Google Docs). I hope you enjoyed reading this as much as I enjoyed writing and programming it.

    You can find the source code used for this post in the repository linked below.

    References

  • Testing an iOS Location Manager

    Testing an iOS Location Manager

    This post explains how to validate hardware-dependent components like the LocationManager, which relies on GPS hardware. Testing such managers, including LocationManager and VideoManager, is crucial for addressing challenges developers face, such as hardware constraints, environmental variability, and simulator limitations. By mastering these techniques, you can ensure robust and reliable application behavior in real-world scenarios.

    I will guide you through the process of validating a LocationManager, introduce its test support structures, and provide examples of unit tests. Along the way, we’ll explore key techniques like mocking system services, dependency injection, and efficient testing strategies for simulators and real devices.

    This improved version enhances clarity, reduces redundancy, and improves flow while retaining all the critical details. Let me know if you’d like further refinements!

    Location Manager

    In this case, we have a location manager to handle geographic data efficiently and ensure accurate location tracking.

    import Foundation
    import CoreLocation
    
    @globalActor
    actor GlobalManager {
        static var shared = GlobalManager()
    }
    
    @GlobalManager
    class LocationManager: NSObject, ObservableObject  {
        private var clLocationManager: CLLocationManager? = nil
    
        @MainActor
        @Published var permissionGranted: Bool = false
        private var internalPermissionGranted: Bool = false {
             didSet {
                Task { [internalPermissionGranted] in
                    await MainActor.run {
                        self.permissionGranted = internalPermissionGranted
                    }
                }
            }
        }
        
        @MainActor
        @Published var speed: Double = 0.0
        private var internalSpeed: Double = 0.0 {
             didSet {
                Task { [internalSpeed] in
                    await MainActor.run {
                        self.speed = internalSpeed
                    }
                }
            }
        }
        
        init(clLocationManager: CLLocationManager = CLLocationManager()) {
            super.init()
            self.clLocationManager = clLocationManager
            clLocationManager.delegate = self
        }
        
        func checkPermission() {
            clLocationManager?.requestWhenInUseAuthorization()
        }
    }
    
    extension LocationManager: @preconcurrency CLLocationManagerDelegate {
        
        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            let statuses: [CLAuthorizationStatus] = [.authorizedWhenInUse, .authorizedAlways]
            if statuses.contains(status) {
                internalPermissionGranted = true
                Task {
                    internalStartUpdatingLocation()
                }
            } else if status == .notDetermined {
                checkPermission()
            } else {
                internalPermissionGranted = false
            }
        }
        
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            guard let location = locations.last else { return }
            internalSpeed = location.speed
        }
        
        private func internalStartUpdatingLocation() {
            guard CLLocationManager.locationServicesEnabled() else { return }
            clLocationManager?.startUpdatingLocation()
        }
    }
    
    This Swift code defines a LocationManager class that manages location permissions and tracking, integrating with SwiftUI’s reactive model. It uses CLLocationManager to handle location updates and authorization, updating @Published properties like permissionGranted and speed for UI binding. The class leverages Swift’s concurrency features, including @MainActor and @globalActor, to ensure thread-safe updates to the UI on the main thread. Private properties (internalPermissionGranted and internalSpeed) encapsulate internal state, while public @Published properties notify views of changes. By conforming to CLLocationManagerDelegate, it handles permission requests, starts location updates, and updates speed in response to location changes, ensuring a clean, reactive, and thread-safe integration with SwiftUI.

    Location Manager

    The key is to mock CLLocationManager and override its methods to suit the needs of your tests:

    class LocationManagerMock: CLLocationManager {
        var clAuthorizationStatus: CLAuthorizationStatus = .notDetermined
        
        override func requestWhenInUseAuthorization() {
            delegate?.locationManager!(self, didChangeAuthorization: clAuthorizationStatus)
        }
        
        override func startUpdatingLocation() {
            let sampleLocation = CLLocation(
                coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
                altitude: 10.0,
                horizontalAccuracy: 5.0,
                verticalAccuracy: 5.0,
                course: 90.0,
                speed: 10.0,
                timestamp: Date()
            )
            delegate?.locationManager!(self, didUpdateLocations: [sampleLocation])
        }
    }

    For our test purposes, we are validating the location-granted request service and starting the location update process. During permission validation, we use an attribute to provide the desired response when requestWhenInUseAuthorization is executed. Additionally, we include a sample CLLocation to simulate the location data when startUpdatingLocation is called.

    To ensure robust validation of authorization, we have implemented the following unit tests:

        @Test func testAthorizacionRequestDenied() async throws {
            let locationManagerMock = LocationManagerMock()
            locationManagerMock.clAuthorizationStatus = .denied
            let sut = await LocationManager(clLocationManager: locationManagerMock)
            await sut.checkPermission()
            // Wait for the @Published speed property to update
            try await Task.sleep(nanoseconds: 1_000_000)
            await #expect(sut.permissionGranted == false)
        }
    
    
        @Test func testAthorizacionRequestAuthorized() async throws {
            let locationManagerMock = LocationManagerMock()
            locationManagerMock.clAuthorizationStatus =  .authorizedWhenInUse
            let sut = await LocationManager(clLocationManager: locationManagerMock)
            await sut.checkPermission()
            // Wait for the @Published speed property to update
            try await Task.sleep(nanoseconds: 1_000_000)
            await #expect(sut.permissionGranted == true)
        }
    Validates scenarios where the user grants or denies location services authorization. Also validates location updates.
        @Test func testStartUpdatingLocation() async throws {
            let locationManagerMock = LocationManagerMock()
            locationManagerMock.clAuthorizationStatus =  .authorizedWhenInUse
            let sut = await LocationManager(clLocationManager: locationManagerMock)
            await sut.checkPermission()
            // Wait for the @Published speed property to update
            try await Task.sleep(nanoseconds: 50_000_000)
                   
            await #expect(sut.speed == 10.00)
        }

    Basically we check location speed.

    Conclusions

    In this post, I have presented a method for validating hardware-dependent issues, such as GPS information. You can find the source code used for this post in the repository linked below.