我收到的错误是我的班级不符合NSObjectProtocol,我不知道这意味着什么。我已经实现了WCSessionDelegate的所有功能,所以这不是问题。有人知道问题是什么吗?谢谢!
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]) {
}
}
答案 0 :(得分:188)
请参阅Why in swift we cannot adopt a protocol without inheritance a class from NSObject?
简而言之,WCSessionDelegate
本身继承自NSObjectProtocol
,因此您也需要在该协议中实现方法。实现这些方法的最简单方法是子类NSObject
:
class BatteryLevel: NSObject, WCSessionDelegate
请注意,您在此处理Obj-C API。