Class does not conform NSObjectProtocol

SwiftClass

Swift Problem Overview


I get an error that my class doesn't conform the NSObjectProtocol, I don't know what this means. I have implemented all the function from the WCSessionDelegate so that is not the problem. Does somebody know what the issue is? Thanks!

import Foundation
import WatchConnectivity

class BatteryLevel: WCSessionDelegate {
    
    
    var session: WCSession? {
        didSet {
            if let session = session {
                session.delegate = self
                session.activate()
            }
        }
    }
    
    var batteryStatus = 0.0;
    
    func getBatteryLevel(){
        if WCSession.isSupported() {
            // 2
            session = WCSession.default()
            // 3
            session!.sendMessage(["getBatteryLevel": ""], replyHandler: { (response) -> Void in
                if (response["batteryLevel"] as? String) != nil {
                    self.batteryStatus = (response["batteryLevel"] as? Double)! * 100
                }
            }, errorHandler: { (error) -> Void in
                // 6
                print(error)
            })
        }}
    
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
    }
}

Swift Solutions


Solution 1 - Swift

See https://stackoverflow.com/questions/24650325/why-in-swift-we-cannot-adopt-a-protocol-without-inheritance-a-class-from-nsobjec

In short, WCSessionDelegate itself inherits from NSObjectProtocol therefore you need to implement methods in that protocol, too. The easiest way to implement those methods is to subclass NSObject:

class BatteryLevel: NSObject, WCSessionDelegate

Note that you are dealing with Obj-C APIs here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionda1lbi3View Question on Stackoverflow
Solution 1 - SwiftSulthanView Answer on Stackoverflow