Swift WatchOS2的调试建议
我已经阅读了WatchOS 2中的例子,这本教程是由位于的团队编写的,特别是第18章。它们都很好用。在我自己的应用程序中,我试图从手表上发送一个按钮来启动iPhone应用程序上的一个按钮。以下是手表和手机上的Swift相关代码: 观察:Swift WatchOS2的调试建议,swift,watchkit,watchos-2,Swift,Watchkit,Watchos 2,我已经阅读了WatchOS 2中的例子,这本教程是由位于的团队编写的,特别是第18章。它们都很好用。在我自己的应用程序中,我试图从手表上发送一个按钮来启动iPhone应用程序上的一个按钮。以下是手表和手机上的Swift相关代码: 观察: // // InterfaceController.swift // Wasted Time Extension // // Created by Michael Rowe on 7/21/15. // Copyright © 2010-2015 Mic
//
// InterfaceController.swift
// Wasted Time Extension
//
// Created by Michael Rowe on 7/21/15.
// Copyright © 2010-2015 Michael Rowe. All rights reserved.
//
import WatchKit
import WatchConnectivity
import Foundation
class InterfaceController: WKInterfaceController,WCSessionDelegate {
@IBOutlet var wasteLabel: WKInterfaceLabel!
@IBOutlet var costLabel: WKInterfaceLabel!
@IBOutlet var counter: WKInterfaceLabel!
@IBOutlet var statusButton: WKInterfaceButton!
// our watchconnective session
var session : WCSession?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
if(WCSession.isSupported()){
session = WCSession.defaultSession()
session!.delegate = self
session!.activateSession()
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func session(session: WCSession, didReceiveMessage message: [String: AnyObject], replyHandler: [String: AnyObject] -> Void) {
print("Did receive message Watch \(message)")
}
@IBAction func addButtonPressed() {
// Pull values from the Phone for current meeting cost, waste costs, and people in meeting
let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")!
var counterd = prefs.doubleForKey("keyPeopleInMeeting")
counterd++
counter.setText(String(format:"%9.0f", counterd))
// Sending data to iPhone via Interactive Messaging
if WCSession.isSupported(){
// we have a watch supporting iPhone
let session = WCSession.defaultSession()
// we can reach the watch
if session.reachable {
let message = ["add": "1"]
print("Message \(message)")
session.transferUserInfo(message)
print("Send Message Add - People \(counterd)")
}
}
if WCSession.isSupported() {
let session = WCSession.defaultSession()
if session.reachable {
let message = ["add":"1"]
session.sendMessage(message, replyHandler: { ( reply: [String: AnyObject]) -> Void in
print("Reply: \(reply)")
}, errorHandler: { (error: NSError) -> Void in
print("ERROR Watch: \(error.localizedDescription)")
})
} else { // reachable
self.showReachabilityError()
}
}
print("Watch Add Button Pressed \(counterd)")
}
@IBAction func minusButtonPressed() {
// Pull values from the Phone for current meeting cost, waste costs, and people in meeting
let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")!
var counterd = prefs.doubleForKey("keyPeopleInMeeting")
counterd--
if (counterd <= 1) {
counterd = 1
}
counter.setText(String(format:"%9.0f", counterd))
if WCSession.isSupported() {
let session = WCSession.defaultSession()
if session.reachable {
let message = ["minus":"1"]
session.sendMessage(message, replyHandler: { ( reply: [String: AnyObject]) -> Void in
print("Reply: \(reply)")
}, errorHandler: { (error: NSError) -> Void in
print("ERROR Watch: \(error.localizedDescription)")
})
} else { // reachable
self.showReachabilityError()
}
}
print("Watch Minus Button Pressed \(counterd)")
}
func statusButtonPressed() {
// Pull values from the Phone for current meeting cost, waste costs, and people in meeting
let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")!
let status = statusButton.description
if WCSession.isSupported() {
let session = WCSession.defaultSession()
if session.reachable {
let message = ["status":status]
session.sendMessage(message, replyHandler: { ( reply: [String: AnyObject]) -> Void in
print("Reply: \(reply)")
}, errorHandler: { (error: NSError) -> Void in
print("ERROR Watch: \(error.localizedDescription)")
})
} else { // reachable
self.showReachabilityError()
}
}
print("Watch Status Button Pressed - Status \(statusButton)")
}
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]){
let prefs:NSUserDefaults = NSUserDefaults(suiteName: "a.b.c")!
if let waste = applicationContext["waste"] as? Float {
print("Watch Receive - Waste \(waste)")
}
if let cost = applicationContext["cost"] as? Float {
print("Watch Receive - Cost \(cost)")
}
if let counternum = applicationContext["counter"] as? Float {
print("Watch Receive - Counter \(counternum)")
}
if let status = applicationContext["status"] as? String {
print("Watch Receive - Status \(status)")
statusButton.setTitle(status)
}
}
private func showReachabilityError() {
let tryAgain = WKAlertAction(title: "Try Again", style: .Default, handler: { () -> Void in })
let cancel = WKAlertAction(title: "Cancel", style: .Cancel, handler: { () -> Void in })
self.presentAlertControllerWithTitle("Your iPhone is not reachable.", message: "You cannot adjust the status or number of attendees Watch is not currently connected to your iPhone. Please ensure your iPhone is on and within range of your Watch.", preferredStyle: WKAlertControllerStyle.Alert, actions:[tryAgain, cancel])
}
func session(session: WCSession, didFinishUserInfoTransfer userInfoTransfer: WCSessionUserInfoTransfer, error: NSError?) {
print("Transfer User Info Error watch: \(error)")
}
}
我在手表上看到消息,并在调试日志中看到它们。。。但他们似乎没有在电话里开火。手机正在成功地向手表发送信息
我已经在模拟器、手表和iPhone上测试了这段代码。请注意,从iPhone到手表的消息是使用via updateApplicationContext完成的,而我正试图使用send message将消息从手表发送到iPhone。以下是用于发送上下文的iPhone代码示例:
if WCSession.isSupported() {
if session.watchAppInstalled {
let UserInfo = ["waste":Float((wastedAmount.text! as NSString).floatValue), "cost":Float((totalAmount.text! as NSString).floatValue), "counter":Float((peopleInMeeting.text! as NSString).floatValue), "status":"Start"]
do {
try session.updateApplicationContext(UserInfo as! [String : AnyObject])
} catch {
print("Updating the context failed: ")
}
}
}
当你说: 我在手表上看到消息,并在调试日志中看到它们。。。但他们似乎没有在电话里开火。手机正在成功地向手表发送信息 然而,一个常见的情况是iPhone代码实际上工作正常,而您唯一看不到的是打印到控制台的调试语句。这似乎是可能的,因为您说您正在看到预期的监视消息,可能包括来自
print(“Reply:\(Reply)”)
的消息。这表示iPhone正在处理该消息
在这种情况下,您通常只希望同时看到来自Watch和iOS模拟器进程的调试控制台消息,但实际上您只连接到其中一个进程。这里(至少)可以做两件事:
Debug>attachtoprocess…
并在“可能的目标”下选择iPhone应用程序在运行iPhone应用程序时在Watch OS中进行调试,在Xcode-8.1中反之亦然。需要附加所需的运行进程 视觉上:-
向
Double
的演员阵容成功了吗?计数器听起来像是一个Int
?对Double的转换成功了。在监视端,您是否实现了func会话(会话:WCSession,didFinishUserInfoTransfer:WCSessionUserInfoTransfer,错误:NSError?
?它是否接收到任何带有错误的回调?我还没有实现,现在将这样做,看看它是否提供了额外的细节。。请参阅代码:if WCSession.isSupported(){let session=WCSession.defaultSession()if session.reachable{let message=[“减号”:“1”]session.sendMessage(message,replyHandler:{(reply:[String:AnyObject])->打印无效(“reply:(reply)”)},errorHandler:{(error:NSError)->打印时无效(“错误监视:(error.localizedDescription)”)}其他{//reachable self.showReachabilityError()}
if WCSession.isSupported() {
if session.watchAppInstalled {
let UserInfo = ["waste":Float((wastedAmount.text! as NSString).floatValue), "cost":Float((totalAmount.text! as NSString).floatValue), "counter":Float((peopleInMeeting.text! as NSString).floatValue), "status":"Start"]
do {
try session.updateApplicationContext(UserInfo as! [String : AnyObject])
} catch {
print("Updating the context failed: ")
}
}
}