我一直在为 WCSession 使用 NatashaTheRobot 单例,但无法让 sendMessage 正常工作。
我的目标是从 Watch 应用程序向 iOS 应用程序发送消息,并将字典从 iOS 应用程序传输到手表应用程序。
这是我在ExtensionDelegate中的代码
import WatchKit
import WatchConnectivity
class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
var session:WCSession!
var boolCheck = Int()
func applicationDidFinishLaunching() {
WatchSessionManager.sharedManager.startSession()
print("Here i am")
}
func applicationDidBecomeActive() {
print("I AWOKE")
}
func applicationWillResignActive() {
}
}
class WatchSessionManager: NSObject, WCSessionDelegate {
static let sharedManager = WatchSessionManager()
private override init() {
super.init()
}
private let session: WCSession = WCSession.defaultSession()
func startSession() {
session.delegate = self
session.activateSession()
if WCSession.isSupported(){
self.session.sendMessage(["b":"peek"], replyHandler: nil, errorHandler: nil)
print("works")
} else {
print("don't work")
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
let sweetN = message["b"]! as? String
dispatch_async(dispatch_get_main_queue(), {
if sweetN == "insertData1" {
NSNotificationCenter.defaultCenter().postNotificationName("sweetData1", object: nil)
})
}
func sendMessage(message: [String : AnyObject],
replyHandler: (([String : AnyObject]) -> Void)? = nil,
errorHandler: ((NSError) -> Void)? = nil)
{
session.sendMessage(message, replyHandler: replyHandler, errorHandler: errorHandler)
print("this is message \(replyHandler)")
var pretty = replyHandler
}
这是我在 iOS 应用程序的WCSingleton中的代码(与 AppDelegate 分开)
import WatchConnectivity
@available(iOS 9.0, *)
class WatchSessionManager: NSObject, WCSessionDelegate {
static let sharedManager = WatchSessionManager()
private override init() {
super.init()
}
private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil
private var validSession: WCSession? {
if let session = session where session.paired && session.watchAppInstalled {
return session
}
return nil
}
func startSession() {
session?.delegate = self
session?.activateSession()
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
//receieve messages from watch
print(message["b"]! as? String)
let sweetN = message["b"]! as? String
dispatch_async(dispatch_get_main_queue(), {
if sweetN == "peek"{
NSNotificationCenter.defaultCenter().postNotificationName("giveMeInfo", object: nil)
}
}
})
}
@available(iOS 9.0, *)
extension WatchSessionManager {
func sendMessage(message: [String : AnyObject],
replyHandler: (([String : AnyObject]) -> Void)? = nil,
errorHandler: ((NSError) -> Void)? = nil)
{
session!.sendMessage(message, replyHandler: replyHandler, errorHandler: errorHandler)
}
}
这是我在ViewController中使用的方法(从 触发NSNotificationCenter
)。然而,这部分代码永远不会被执行(这很奇怪,因为当我使用 applicationContext 时它工作得很好)。
func giveMeInfo(){
let linesAdd1 = linesAdd as! AnyObject
WatchSessionManager.sharedManager.sendMessage(["a":linesAdd1])
}
任何关于如何让所有这些部分协同工作的见解都非常受欢迎!