来自iOS的apple watch触觉反馈



我想有一些类似于iOS上的计时器应用程序正在做的事情-它以某种方式与apple watch同步并在两个设备上运行计时器。不知道他们是怎么做到的,有什么想法吗?

在Apple Watch和iPhone之间同步计时器等应用程序需要使用多种通信技术。例如:

您的主要焦点将放在WatchConnectivity框架上,因为它是最重要的在这个场景中很重要

  • 蓝牙:这项技术允许设备之间进行无线连接和通信。通过使用蓝牙,iPhone和Apple Watch可以建立连接并相互传输数据。

  • iCloud:这是苹果的云存储和同步服务,允许用户在多个设备上存储和访问他们的数据。通过使用iCloud,该应用程序可以在云中存储数据,并在iPhone和Apple Watch上访问数据,即使设备没有通过蓝牙连接。

  • WatchConnectivity框架:这个框架为iPhone和Apple Watch之间的通信和数据传输提供了必要的工具和api。通过使用WatchConnectivity框架,应用程序可以在两台设备之间建立连接并根据需要传输数据。

你以Timer应用程序为例。计时器应用程序需要使用WatchConnectivity框架,如上所述。下面是两个设备的实际情况(这需要创建一个用户界面,但这是应用程序的本质):

iPhone

import UIKit
import WatchConnectivity
class ViewController: UIViewController, WCSessionDelegate {

// MARK: Properties
var timer: Timer?
var session: WCSession?
var startTime: Date?

// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Configure Watch Connectivity
if WCSession.isSupported() {
session = WCSession.default
session?.delegate = self
session?.activate()
}
}

// MARK: Action
@IBAction func startTapped(_ sender: Any) {
startTime = Date()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
// Send start time to Watch
sendStartTimeToWatch()
}

@IBAction func stopTapped(_ sender: Any) {
// Stop timer
timer?.invalidate()
timer = nil
}

// MARK: Helper
@objc func updateTimer() {
// Calculate time elapsed
guard let startTime = startTime else { return }
let timeElapsed = Date().timeIntervalSince(startTime)
// Format time
let minutes = Int(timeElapsed) / 60 % 60
let seconds = Int(timeElapsed) % 60
// Update label
let timerString = String(format:"%02i:%02i", minutes, seconds)
// Update label
// Your label here
}

func sendStartTimeToWatch() {
guard let startTime = startTime, let session = session else { return }
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: startTime, requiringSecureCoding: true)
try session.updateApplicationContext(["startTime": data])
} catch {
print("Error: (error)")
}
}

// MARK: WCSessionDelegate
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// no-op
}

}

苹果看

import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController, WCSessionDelegate {

// MARK: Properties
var timer: Timer?
var session: WCSession?
var startTime: Date?

// MARK: Lifecycle
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure Watch Connectivity
if WCSession.isSupported() {
session = WCSession.default
session?.delegate = self
session?.activate()
}
}

// MARK: Action
@IBAction func startTapped() {
// Receive start time from iPhone
receiveStartTimeFromiPhone()
}

@IBAction func stopTapped() {
// Stop timer
timer?.invalidate()
timer = nil
}

// MARK: Helper
func startTimer() {
guard let startTime = startTime else { return }
// Calculate time elapsed
let timeElapsed = Date().timeIntervalSince(startTime)
// Format time
let minutes = Int(timeElapsed) / 60 % 60
let seconds = Int(timeElapsed) % 60
// Update label
let timerString = String(format:"%02i:%02i", minutes, seconds)
// Update label
// Your label here

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}

@objc func updateTimer() {
guard let startTime = startTime else { return }
// Calculate time elapsed
let timeElapsed = Date().timeIntervalSince(startTime)
// Format time
let minutes = Int(timeElapsed) / 60 % 60
let seconds = Int(timeElapsed) % 60
// Update label
let timerString = String(format:"%02i:%02i", minutes, seconds)
// Update label
// Your label here
}

func receiveStartTimeFromiPhone() {
guard let session = session else { return }
session.sendMessage(["request": "startTime"], replyHandler: { (response) in
if let data = response["startTime"] as? Data, let startTime = try? NSKeyedUnarchiver.unarchivedObject(ofClass: Date.self, from: data) {
self.startTime = startTime
self.startTimer()
}
}, errorHandler: { (error) in
print("Error: (error)")
})
}

// MARK: WCSessionDelegate
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// no-op
}

}

最新更新