我需要实现一个 WatchKit 的 force-touch
我意识到每个类都需要至少一个指定的初始化器。我猜这是关键吗?
顺便说一下,当我使用模拟器时,“ saveSession() reached ”打印语句记录到控制台,但在使用设备时则没有记录。即使在使用设备时,所有其他打印语句也会记录到控制台。有点奇怪。
我的初始化尝试会引发各种错误,例如:
MenuItem
,调用一个位于不继承 WKInterfaceController
的独立类中的 saveWorkout()
方法。我意识到每个类都需要至少一个指定的初始化器。我猜这是关键吗?
顺便说一下,当我使用模拟器时,“ saveSession() reached ”打印语句记录到控制台,但在使用设备时则没有记录。即使在使用设备时,所有其他打印语句也会记录到控制台。有点奇怪。
我的初始化尝试会引发各种错误,例如:
1. 类“DashboardController”的未实现初始化器 'init()' 的致命错误
2. 在调用时缺少参数“context”
Dashboard.swift
class DashboardController: WKInterfaceController {
@IBOutlet var timerLabel: WKInterfaceTimer!
@IBOutlet weak var milesLabel: WKInterfaceLabel!
// var wSM: WorkoutSessionManager
//init(wSM: WorkoutSessionManager) {
// self.wSM = wSM
// super.init()
// }
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
addMenuItemWithItemIcon(.Accept, title: "Save", action: #selector(DashboardController.saveSession))
}
override func willActivate() {
super.willActivate()
print("Dashboard controller reached")
}
func saveSession() {
//wSM.saveWorkout()
print("saveSession() reached")
}
WorkoutSessionManager.swift
class WorkoutSessionContext {
let healthStore: HKHealthStore
let activityType: HKWorkoutActivityType
let locationType: HKWorkoutSessionLocationType
init(healthStore: HKHealthStore, activityType: HKWorkoutActivityType = .Other, locationType: HKWorkoutSessionLocationType = .Unknown) {
self.healthStore = healthStore
self.activityType = activityType
self.locationType = locationType
}
}
protocol WorkoutSessionManagerDelegate: class {
// ... protocol methods
}
class WorkoutSessionManager: NSObject, HKWorkoutSessionDelegate {
let healthStore: HKHealthStore
let workoutSession: HKWorkoutSession
init(context: WorkoutSessionContext) {
self.healthStore = context.healthStore
self.workoutSession = HKWorkoutSession(activityType: context.activityType, locationType: context.locationType)
self.currentActiveEnergyQuantity = HKQuantity(unit: self.energyUnit, doubleValue: 0.0)
self.currentDistanceQuantity = HKQuantity(unit: self.distanceUnit, doubleValue: 0.0)
super.init()
self.workoutSession.delegate = self
}
func saveWorkout() {
guard let startDate = self.workoutStartDate, endDate = self.workoutEndDate else {return}
// ...code...
saveWorkout()
函数(在您的WorkoutSessionManager类中)的guard
语句之前放置一个打印语句,会发生什么? - jamesklet wSM = WorkoutSessionManager()
语句和saveSession()
函数时,您会遇到哪个错误? - jamesk