top of page

Nearby Interaction in SwiftUI: The Magical Playground of (In)Visibility✨

Come along as we delve into the magical world of SwiftUI and Nearby Interaction, where we’ll make friends with devices that can’t even see each other!


Welcome, adventurous coder, to the realm of the magical invisible! ✨ Have you ever wished you could create an app that enables interaction between devices without them having to see each other? Well, you’re in luck! With SwiftUI and Nearby Interaction, we’re about to embark on a thrilling quest to develop such an app, one that will surely amaze your friends and leave them begging for more!


In this enchanting article, we’ll be using SwiftUI, the charming and straightforward UI framework from Apple, combined with the powerful Nearby Interaction framework. Get ready to roll up your sleeves and sprinkle some fairy dust as we dive into the world of (in)visibility!


A Spellbinding Introduction to SwiftUI and Nearby Interaction


SwiftUI is Apple’s delightful, declarative UI toolkit that allows developers to create stunning user interfaces with ease. The beauty of SwiftUI lies in its simplicity and the ability to create reusable components that can be used throughout your app.

Nearby Interaction, on the other hand, is a framework that enables developers to create apps that can sense and communicate with nearby devices, without any visual or physical connection. Think of it as a magical connection between devices that transcends the barriers of space and time (well, not really time, but you get the idea).


Brewing the Potion: Setting Up Your Project


To get started on this enchanting journey, we need to create a new SwiftUI project in Xcode. Don’t forget to add the Nearby Interaction framework to your project by importing it:

import NearbyInteraction


Summoning the Magical Session


Once you’ve set up your project, it’s time to create a NIConfiguration and a magical session that will allow our devices to communicate with one another:

var configuration = NIConfiguration()
var nearbySession: NISession?

In this mystical realm, our devices need to share some secrets (also known as tokens) to identify each other. Make sure you create and share these secrets between the devices involved:

configuration.token = yourSharedToken

With our configuration in place, we can create an NISession and assign its delegate:

nearbySession = NISession()
nearbySession?.delegate = self


Preparing the Enchantment: Implementing the Delegate Methods


To receive and handle updates from the Nearby Interaction framework, we need to implement the NISessionDelegatemethods:

extension ContentView: NISessionDelegate {
    func session(_ session: NISession, didUpdate nearbyObjects: [NINearbyObject]) {
        // Handle updates from nearby devices here
    }

    func session(_ session: NISession, didRemove nearbyObjects: [NINearbyObject], with reason: NINearbyObject.RemovalReason) {
        // Handle removal of nearby devices here
    }
}


Casting the Spell: Running the Nearby Interaction Session


Now that our cauldron is bubbling with code, it’s time to cast the spell by running the Nearby Interaction session:

nearbySession?.run(configuration)

Voilà! Your devices can now sense and communicate with one another, even if they’re invisible to the human eye! 🎉


The Enchanted SwiftUI Interface


With the core magic in place, it’s time to build an engaging SwiftUI interface that will display our (in)visible connections. Let’s create a simple view that shows the nearby devices and their distance from the user’s device:

import SwiftUI

struct ContentView: View {
    @State private var nearbyDevices: [NINearbyObject] = []
    
    var body: some View {
        NavigationView {
            List(nearbyDevices, id: \.self) { device in
                VStack(alignment: .leading) {
                    Text(device.description)
                        .font(.headline)
                    Text("Distance: \(device.distance.stringValue) meters")
                        .font(.subheadline)
                        .foregroundColor(.gray)
                }
            }
            .navigationTitle("Nearby Devices")
        }
    }
}

To keep our interface updated with the latest information, we need to modify our NISessionDelegate methods to update the nearbyDevices array when there are changes:

extension ContentView: NISessionDelegate {
    func session(_ session: NISession, didUpdate nearbyObjects: [NINearbyObject]) {
        DispatchQueue.main.async {
            self.nearbyDevices = nearbyObjects
        }
    }

    func session(_ session: NISession, didRemove nearbyObjects: [NINearbyObject], with reason: NINearbyObject.RemovalReason) {
        DispatchQueue.main.async {
            self.nearbyDevices.removeAll(where: { removedObject in
                nearbyObjects.contains(removedObject)
            })
        }
    }
}

And there you have it! You’ve successfully ventured through the mystical realm of SwiftUI and Nearby Interaction, creating a magical app that can sense and communicate with devices that are seemingly invisible. 🌟


As you leave this enchanting world and return to reality, remember that you’re now equipped with the powerful tools of SwiftUI and Nearby Interaction. Keep experimenting, and you’ll create even more magical experiences for your users.

Happy coding, and may the magic be with you always! 🧙🏿‍♂️✨


Give Support or Tip👋🏿


Give a Tip with CashApp: https://cash.app/$DiAlcatic

23 views0 comments

Comments


bottom of page