Class does not conform NSObjectProtocol – Class

Photo of author
Written By M Ibrahim
abstract-class rx-swift

Quick Fix: To conform to NSObjectProtocol, subclass NSObject class. This allows Swift to inherit required methods from NSObjectProtocol implemented in the NSObject superclass.

The Problem:

I am facing an issue with my Swift code where I am trying to create a class that adopts the WCSessionDelegate protocol. However, I am getting an error message stating that class does not conform to NSObjectProtocol. I have implemented all the required delegate methods from WCSessionDelegate`, but the error persists, leaving me confused about the cause of this issue. I would appreciate any insights or suggestions on how to resolve this problem. Please provide a comprehensive explanation for clarity and a concise solution.

The Solutions:

Solution 1: Use NSObject as a Base Class for Your Delegate Class

The error message “Class does not conform to the NSObjectProtocol” occurs when you attempt to use a class as a delegate for an Objective-C API without inheriting from `NSObject`. To resolve this issue, you can subclass `NSObject` and then implement the required delegate methods in your custom class. Here’s an enhanced version of the code you shared:

import Foundation
import WatchConnectivity

class BatteryLevel: NSObject, WCSessionDelegate {

    var session: WCSession? {
        didSet {
            if let session = session {
                session.delegate = self
                session.activate()
            }
        }
    }

    var batteryStatus = 0.0

    func getBatteryLevel() {
        if WCSession.isSupported() {
            // Establish the session and send a message to retrieve the battery level.
            session = WCSession.default()
            session!.sendMessage(["getBatteryLevel": ""], replyHandler: { (response) in
                if let batteryLevel = response["batteryLevel"] as? String {
                    self.batteryStatus = (Double(batteryLevel) ?? 0.0) * 100
                }
            }, errorHandler: { (error) in
                // Handle the error appropriately.
                print(error)
            })
        }
    }

    // Override the required delegate methods to handle incoming messages and session activation events.

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        // Handle the activation completion with the appropriate logic.
    }

    func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
        // Process the received message from the companion app.
    }
}

By subclassing `NSObject`, your `BatteryLevel` class now conforms to the `NSObjectProtocol`, and you can use it as a delegate for the `WCSession`. This should resolve the error you were encountering.