没有触觉反馈

时间:2017-02-20 17:39:39

标签: swift watch-os-3 haptic-feedback

我的watchos应用程序依赖于在后台工作的触觉反馈。我已经在互联网上搜索和搜索了如何做到这一点,并且只学习了如何将信息添加到我的info.plist

我不想使用通知来提醒我的用户,因为它在UI方面很麻烦,因为这样做太频繁了。

我读过有关锻炼课程的内容,但无法使其发挥作用。

手腕降低时,如何让触觉反馈工作?最简单的方法就足够了,我不是swift最先进的,所以请尽量解释一下!

我的代码示例如下。如果我想要背景触觉反馈工作,请告诉我把它放在哪里:

我的计时器:

 _ = Timer.scheduledTimer(timeInterval: 88, target: self, selector: "action", userInfo: nil, repeats: true)

我的行动:

 func action() {
    print("action")
    WKInterfaceDevice.current().play(.success)
     imageObject.setImageNamed("number2")     
}

这就是我在HKWorkout会议上所做的事情,但绝对不知道最新情况。

  func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
    switch toState {
    case .running:
        workoutDidStart(date)
    case .ended:
        workoutDidEnd(date)
    default:
        print("Unexpected state \(toState)")
    }
}

func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
    // Do nothing for now
    print("Workout error")
}


func workoutDidStart(_ date : Date) {
    if let query = createHeartRateStreamingQuery(date) {
        self.currenQuery = query
        healthStore.execute(query)
    } else {
        label.setText("cannot start")
    }
}

func workoutDidEnd(_ date : Date) {
    healthStore.stop(self.currenQuery!)
    label.setText("---")
    session = nil
}

// MARK: - Actions
@IBAction func startBtnTapped() {
    if (self.workoutActive) {
        //finish the current workout
        self.workoutActive = false
        self.startStopButton.setTitle("Start")
        if let workout = self.session {
            healthStore.end(workout)
        }
    } else {
        //start a new workout
        self.workoutActive = true
        self.startStopButton.setTitle("Stop")
        _ = Timer.scheduledTimer(timeInterval: 5, target: self, selector: "firsts", userInfo: nil, repeats: false)


        startWorkout()
    }

}

func startWorkout() {

    // If we have already started the workout, then do nothing.
    if (session != nil) {
        return
    }

    // Configure the workout session.
    let workoutConfiguration = HKWorkoutConfiguration()
    workoutConfiguration.activityType = .crossTraining
    workoutConfiguration.locationType = .indoor

    do {
        session = try HKWorkoutSession(configuration: workoutConfiguration)
        session?.delegate = self
    } catch {
        fatalError("Unable to create the workout session!")
    }

    healthStore.start(self.session!)
}

func createHeartRateStreamingQuery(_ workoutStartDate: Date) -> HKQuery? {


    guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { return nil }
    let datePredicate = HKQuery.predicateForSamples(withStart: workoutStartDate, end: nil, options: .strictEndDate )
    //let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
    let predicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate])


    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: predicate, anchor: nil, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
        //guard let newAnchor = newAnchor else {return}
        //self.anchor = newAnchor
        self.updateHeartRate(sampleObjects)
    }

    heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
        //self.anchor = newAnchor!
        self.updateHeartRate(samples)
    }
    return heartRateQuery
}

func updateHeartRate(_ samples: [HKSample]?) {
    guard let heartRateSamples = samples as? [HKQuantitySample] else {return}

    DispatchQueue.main.async {
        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValue(for: self.heartRateUnit)
        self.label.setText(String(UInt16(value)))

        // retrieve source from sample
        let name = sample.sourceRevision.source.name
        self.updateDeviceName(name)
        self.animateHeart()
    }
}

func updateDeviceName(_ deviceName: String) {
    deviceLabel.setText(deviceName)
}

func animateHeart() {
    self.animate(withDuration: 0.5) {
        self.heart.setWidth(60)
        self.heart.setHeight(90)
    }

    let when = DispatchTime.now() + Double(Int64(0.5 * double_t(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)

    DispatchQueue.global(qos: .default).async {
        DispatchQueue.main.asyncAfter(deadline: when) {
            self.animate(withDuration: 0.5, animations: {
                self.heart.setWidth(50)
                self.heart.setHeight(80)
            })            }


    }
}

看起来我甚至不需要心率数据或任何东西,除了在后台嗡嗡作响的taptic引擎。

2 个答案:

答案 0 :(得分:4)

作为addition to my previous答案,我创建了一个示例项目,展示了如何在后台触发振动:

有关如何使用HKWorkoutSession的完整示例,请查看my sample project on GitHub。即使应用程序在后台运行,示例应用程序也会每五秒触发一次振动。 HKWorkoutSession因此,仅当应用程序使用包含HealthKit权利的配置文件进行签名时,该示例才有效。请务必将开发团队更改为您自己的团队,以获取所有三个可用目标。 Xcode将尝试创建所需的配置文件。如果存在任何签名问题,或者您使用在后台运行的通配符配置文件将无效。

答案 1 :(得分:2)

这只能使用HKWorkoutSessions。 Apple的App Programming Guide for watchOS清楚地指定了没有HKWorkoutSession的可用后台模式,并且它们都不允许您在后台触发触觉反馈。

使用HKWorkoutSession,您可以实施使用应用跟踪用户锻炼的应用。当HKWorkoutSession正在运行时,您的应用有多种权限:

  

该应用程序在整个锻炼过程中继续运行,甚至   当用户降低他们的手腕或与不同的应用程序交互时。   当用户抬起手腕时,应用程序会重新出现,让用户离开   快速轻松地检查他们当前的进度和表现。

     

该应用程序可以继续从Apple Watch的传感器访问数据   背景,让您随时保持应用程序的最新状态。对于   例如,正在运行的应用可以继续跟踪用户的心率,   确保每当显示最新的心率数据   用户抬起手腕。

     

应用程序可以使用音频或触觉反馈提醒用户   在后台运行。

要使用HKWorkoutSession并提供触觉反馈,您需要将WKBackgroundModes密钥和UIBackgroundModes添加到WatchKit扩展程序的Info.plist中。

<key>WKBackgroundModes</key>
<array>
    <string>workout-processing</string>
</array>
<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

有几点需要注意:

  • 当另一个应用启动另一个WKWorkoutSession时,您的会话将会结束
  • 如果您在后台过度使用资源,您的应用可能会被watchOS暂停
  • 您的应用可能有助于填充配对iPhone上的活动应用中的活动响铃
  • 根据您的应用程序类型,Apple可能会在App Store中发布时拒绝您的应用
  • 需要HealthKit权利(您可以将其添加到Xcode中的功能视图中)

有关如何实施HKWorkoutSession的更详细指南,请查看API Reference

有关如何使用HKWorkoutSession的完整示例,请查看my sample project on GitHub。即使应用程序在后台运行,示例应用程序也会每五秒触发一次振动。 HKWorkoutSession因此,仅当应用程序使用包含HealthKit权利的配置文件进行签名时,该示例才有效。请务必将开发团队更改为您自己的团队,以获取所有三个可用目标。 Xcode将尝试创建所需的配置文件。如果存在任何签名问题,或者您使用在后台运行的通配符配置文件将无效。