无论如何要保持我的WatchKit应用程序在后台运行?

时间:2017-03-02 10:06:03

标签: ios swift watchkit core-motion

我是关于swift和WatchKit框架的新手。我从一个月开始研究这个问题。现在我的问题是:可以在苹果手表上以后台模式运行应用吗?我从文档中读到WatchKit扩展不支持后台执行模式。但是如果真的如此工作如何使用健康应用程序这样的应用程序?我的意思是,在手表上有一个名为health的应用程序,即使是应用程序不在前台。我会做或多或少做同样的事情。在我的应用程序中,我只会在用户移动手表时检测到用户加速,即使应用程序不在前台。我该怎么办?请给我发一份必要的文件。非常感谢!

聚苯乙烯。对不起我的英语不好!

4 个答案:

答案 0 :(得分:1)

在watchOS 3中,锻炼应用程序可以在后台运行。我没有亲身经历,但请查看WWDC 2016视频Building Great Workout Apps

答案 1 :(得分:1)

是的,你可以。有几种方法:

  1. 使用HKWorkoutSession开始锻炼 - 这是最强大的方式,但是您需要使用HealthKit,Apple Watch上只有1个应用可以这样运行。
  2. 使用WKAudioFilePlayer在后台播放音频 - 仅限音频。
  3. WKURLSessionRefreshBackgroundTask适合短期背景更新。
  4. 还有其他后台任务,例如WKSnapshotRefreshBackgroundTaskWKURLSessionRefreshBackgroundTask。它们列在this article的后台任务部分中。
  5. performExpiringActivity(withReason:using:)可以用来在应用程序到达后台时延长应用程序的使用寿命。
  6. 另请阅读Leveraging iOS Technologies

答案 2 :(得分:1)

使用WatchOS 6+,如果您的手表应用属于以下5个用例之一,则可以请求WKExtendedRuntimeSession (see documentation)

  • 自我护理
  • 正念
  • 物理疗法
  • 警报
  • 健康监测

有关WWDC的视频,其中介绍了A$application_date <- as.Date(A$application_date) B$date <- as.Date(B$date) https://developer.apple.com/videos/play/wwdc2019/251/

答案 3 :(得分:0)

我也面临着同样的问题。我想在应用程序处于后台模式时执行一些代码。我已经解决了这个问题。我发现了一种额外的状态,其中我的手表应用程序将继续在后台运行,不需要HKWorkoutSession或上面讨论的任何其他解决方案。只需按照以下步骤

  1. 导入CoreLocation
  2. 在课程中添加CLLocationManagerDelegate
  3. willActive方法中添加以下代码。

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    if #available(watchOSApplicationExtension 3.0, *) {
        locationManager.startUpdatingLocation()
    } else {
        // Fallback on earlier versions
    }
    
    if #available(watchOSApplicationExtension 4.0, *) {
        locationManager.allowsBackgroundLocationUpdates = true
    } else {
       print("Location not updated")
    }
    
  4. 最后,只需添加CLLocationManagerDelegate

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("Location updated\(locations)")
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Location_update_error\(error)")
}

也许可以解决您的问题。

相关问题