Jie*_* Hu 10 ios swift watchos-2
最近,我正在研究一个与Watch/ iPhone通信有关的项目.但是我的代码有时工作并且有时不起作用,这对我来说有点奇怪,因为我认为代码应该工作与否.它不能是50/50.因此,我不知道出了什么问题.
在iPhone上设置WCSession:
class WatchCommunicationController: NSObject, WCSessionDelegate {
var session : WCSession?
override init(){
// super class init
super.init()
// if WCSession is supported
if WCSession.isSupported() { // it is supported
// get default session
session = WCSession.defaultSession()
// set delegate
session!.delegate = self
// activate session
session!.activateSession()
} else {
print("iPhone does not support WCSession")
}
}
... ...
}
Run Code Online (Sandbox Code Playgroud)
Watch上类似的WCSession设置:
class PhoneCommunicationController: NSObject, WCSessionDelegate {
var session : WCSession?
override init(){
// super class init
super.init()
// if WCSession is supported
if WCSession.isSupported() { // it is supported
// get default session
session = WCSession.defaultSession()
// set delegate
session!.delegate = self
// activate session
session!.activateSession()
} else {
print("?Watch does not support WCSession")
}
}
... ...
}
Run Code Online (Sandbox Code Playgroud)
发送消息观察:
func sendGesture(手势:GKGesture){
// if WCSession is reachable
if session!.reachable { // it is reachable
// create the interactive message with gesture
let message : [String : AnyObject]
message = [
"Type":"Gesture",
"Content":gesture.rawValue
]
// send message
session!.sendMessage(message, replyHandler: nil, errorHandler: nil)
print("?Watch send gesture \(gesture)")
} else{ // it is not reachable
print("WCSession is not reachable")
}
Run Code Online (Sandbox Code Playgroud)
}
相关枚举:
enum GKGesture: Int {
case Push = 0, Left, Right, Up, Down
}
Run Code Online (Sandbox Code Playgroud)
在iPhone上收到消息:
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
//retrieve info
let type = message["Type"] as! String
let content = message["Content"]
switch type {
case "Gesture":
handleGesture(GKGesture(rawValue: content as! Int)!)
default:
print("Received message \(message) is invalid with type of \(type)")
}
}
func handleGesture(gesture : GKGesture){
print("iPhone receives gesture \(gesture)")
var notificationName = ""
switch gesture {
case .Up:
notificationName = "GestureUp"
case .Down:
notificationName = "GestureDown"
case .Left:
notificationName = "GestureLeft"
case .Right:
notificationName = "GestureRight"
case .Push:
notificationName = "GesturePush"
}
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil)
}
Run Code Online (Sandbox Code Playgroud)
不知怎的,我无法在Xcode上调试我的Watch应用程序,调试会话就不会附加.我不知道为什么.因此,我只用iPhone调试片面.
有时我打印出"接收手势",有时不打印.同样获取通知也是如此.
小智 6
我不知道在WCSession中传输时是否会将Int包裹到NSNumber.如果它是,那么这必然是为什么当我使用Int作为枚举的基类时,它将无法工作并且当String是基类时有效.
连接已知问题将NSNumber和NSDate对象与WCSession API一起使用时,您的应用可能会崩溃.
解决方法:在调用WCSession API之前,将NSNumber或NSDate对象转换为字符串.在接收方进行相反的转换.
| 归档时间: |
|
| 查看次数: |
7744 次 |
| 最近记录: |