将保存的锻炼从 Watch 传递到 iPhone

Pass saved Workout from Watch to iPhone

在 Watch 上,我可以将保存的锻炼从 WorkoutInterfaceController 传递到 SummaryInterfaceController。但我想知道如何将保存的锻炼从 Watch 传递到 iPhone(这样我也可以在摘要视图控制器中显示它)。

你知道吗?或者有更好的方法吗?

这是我用来将保存的锻炼从 WorkoutInterfaceController 传递到 SummaryInterfaceController 的方法:

private func saveWorkout() {
    // Create and save a workout sample
    let configuration = workoutSession!.workoutConfiguration
    let isIndoor = (configuration.locationType == .indoor) as NSNumber
    print("locationType: \(configuration)")

    let workout = HKWorkout(activityType: configuration.activityType,
                            start: workoutStartDate!,
                            end: workoutEndDate!,
                            workoutEvents: workoutEvents,
                            totalEnergyBurned: totalEnergyBurned,
                            totalDistance: totalDistance,
                            metadata: [HKMetadataKeyIndoorWorkout:isIndoor]);

    healthStore.save(workout) { success, _ in
        if success {
            self.addSamples(toWorkout: workout)
        }
    }

    WKInterfaceController.reloadRootControllers(withNames: ["SummaryInterfaceController"], contexts: [workout])
}

private func addSamples(toWorkout workout: HKWorkout) {
    // Create energy and distance samples
    let totalEnergyBurnedSample = HKQuantitySample(type: HKQuantityType.activeEnergyBurned(),
                                                   quantity: totalEnergyBurned,
                                                   start: workoutStartDate!,
                                                   end: workoutEndDate!)

    // Add samples to workout
    healthStore.add([totalEnergyBurnedSample], to: workout) { (success: Bool, error: Error?) in
        if success {
            // Samples have been added
        }
    }
}

如果有任何问题或需要信息,请告诉我,谢谢!

为此,您必须创建一个应用程序组,它本质上是一个 space 两个应用程序都可以使用的应用程序组。它是在 iOS8 中与 exetension 框架一起引入的,因此应用程序可以与其今日小部件或自定义键盘以及其他应用程序进行通信。

添加功能

我们要做的第一件事是将应用程序组功能添加到我们的 iPhone 和 Watch Watch Extension 目标。

为此打开项目设置(文件列表顶部的蓝色图标)和 select iPhone 目标。您需要 select 页面顶部的“功能”选项卡并向下滚动以打开应用程序组。

这需要连接开发者资料,并且需要一段时间才能启用。您还需要执行相同的步骤来打开手表套件扩展的应用程序组。

接下来您需要确保应用组字符串是您想要的标识符字符串并且对您的应用有意义,它必须以单词组开头,否则会报错。如果您愿意,还可以添加多个组。无论您选择什么,它们都必须使用蓝色勾号启用(同样这可能需要一段时间)并且对于 iPhone 和 Watch 扩展目标完全相同!

要使用 App Groups,它与 NSUserDefaults 没有什么不同或难以使用:

var userDefaults = NSUserDefaults(suiteName: "group.com.example.My-App")
userDefaults.setObject(true, forKey: "isDarkModeEnabled")
userDefaults.synchronize()

这里唯一的区别是 NSUserDefaults 的实例化方式和最后调用同步的方式。您将容器 ID 提供给名为“suiteName”的构造函数参数,然后调用“synchronize()”,您的数据就会飞到云端供其他应用程序和设备使用。

更上一层楼

您可以更进一步,为您的应用创建 class 并为您的属性抽象底层存储。这是一个例子:

public class ConfigurationModel: NSObject {

public static let storageKey = "group.com.example.My-App"
public let userStorage = NSUserDefaults(suiteName: storageKey)

public var isDarkModeEnabled: Bool {
 get {
    // Get setting from storage or default
    if userStorage?.objectForKey("isDarkModeEnabled") == nil {
       userStorage?.setObject(false, forKey: "isDarkModeEnabled")
       userStorage?.synchronize()
    }

     return userStorage?.objectForKey("isDarkModeEnabled")
 }

 set {
    // Set new value in storage
    userStorage?.setObject(newValue, forKey: "isDarkModeEnabled")
    userStorage?.synchronize()
 }
}

在 class 的顶部,我声明了我的组容器 ID 并从中创建了 NSUserDefault 对象。然后我的 class 属性有 getter 和 setter 来将数据存储到应用程序组。如果密钥不存在,它会使用默认值创建它并同步它。从现在开始使用 class 很简单:

var configModel = ConfigurationModel()
configModel.isDarkModeEnabled = true

这个属性存储在云端!一切都为你抽象了。您不必为将其存储和同步到应用程序组而烦恼。这一切都在 getters 和 setters 中自动为您完成!

希望这能帮助您了解如何在 iPhone 和 Apple Watch 应用程序之间共享数据。

作为我研究和开发的一部分,我发现 iPhone 和 Apple Watch 的配对有可能发挥作用。 在这种情况下,点击 Watch 应用程序上的按钮将在 iPhone.

上发送文本

要制作此功能的简单演示,请在 WatchKit 界面上放置一个按钮,并在 iOS 应用程序的故事板上放置一个标签。

现在,将按钮作为 IBAction 连接到 WatchKit 界面控制器,以响应按钮点击事件。还将 Label 作为 IBOutlet 连接到 UI View Controller。

在界面控制器中,我们创建一个字符串变量以发送到标签,并在按钮的 IBAction 方法中创建一个包含您创建的字符串变量的字典。该字典是传递给 iPhone 应用程序的内容。

class InterfaceController: WKInterfaceController {
    Var str: String = "Hello Phone"
    @IBAction func button() {
        let dict: Dictionary = ["message": str]
    }

使用以下方法将词典发送到iPhone。

WKInterfaceController.openParentApplication(dict, reply: {(reply, error) -> void in
     print("Reply receive from iPhone app")
})

在iOS应用的AppDelegate中,添加如下应用方法。这将处理来自 Watch 的先前方法通信。我们也可以使用通知来通知视图控制器数据已经收到并传递它。

func application(application: UIApplication, handleWatchkitExtensionRequest userInfo: [NSObject : AnyObject]?, reply:(([NSObject : AnyObject]!) {
    NSNotificationCenter.defaultCenter().postNotificationName("WatchKitReq", object: userInfo)
}

最后在视图控制器中,为将标签文本更新为与数据一起发送的字符串的通知创建一个侦听器。

class ViewController: UIViewController {
        @IBOutlet weak var label: UILabel!
        override func viewDidLoad() {
          super.viewDidLoad()
          NSNotificationCenter.defaultCenter().addObserver(self, selector("handleWatchKitNotification:"), name: "WatchKitReq", object: nil)
}
func handleWatchKitNotification(notification: NSNotification) {
    if let userInfo = notification.object as? [String : String] {
        label.text = userInfo["message"]
    }
}

希望这能帮助您理解。更多问题可以看这里,

Delegate Method