Commit 571eac67f5752379049a5d0279a65788cb06fef4

Authored by 权海
1 parent cd30be80

feat(ui):同步部分代码

... ... @@ -27,24 +27,24 @@ final class HealthDataReader {
startDate: startDate,
endDate: endDate
)
async let activeEnergy = fetchQuantitySamples(
async let activeEnergy = fetchDailyCumulativeSamples(
identifier: .activeEnergyBurned,
dataType: .activeEnergy,
unit: .kilocalorie(),
startDate: startDate,
endDate: endDate
)
async let exercise = fetchQuantitySamples(
async let exercise = fetchDailyCumulativeSamples(
identifier: .appleExerciseTime,
dataType: .exercise,
unit: .minute(),
unit: .second(),
startDate: startDate,
endDate: endDate
)
async let stand = fetchQuantitySamples(
async let stand = fetchDailyCumulativeSamples(
identifier: .appleStandTime,
dataType: .stand,
unit: .minute(),
unit: .second(),
startDate: startDate,
endDate: endDate
)
... ... @@ -203,37 +203,40 @@ final class HealthDataReader {
}
func fetchActiveEnergyData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await fetchQuantitySamples(
identifier: .activeEnergyBurned,
dataType: .activeEnergy,
unit: .kilocalorie(),
startDate: startDate,
endDate: endDate
)
try await fetchDailyCumulativeSamples(identifier: .activeEnergyBurned, dataType: .activeEnergy, unit: .kilocalorie(), startDate: startDate, endDate: endDate)
// try await fetchQuantitySamples(
// identifier: .activeEnergyBurned,
// dataType: .activeEnergy,
// unit: .kilocalorie(),
// startDate: startDate,
// endDate: endDate
// )
}
func fetchExerciseData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await fetchQuantitySamples(
identifier: .appleExerciseTime,
dataType: .exercise,
unit: .minute(),
startDate: startDate,
endDate: endDate
)
try await fetchDailyCumulativeSamples(identifier: .appleExerciseTime, dataType: .exercise, unit: .second(), startDate: startDate, endDate: endDate)
// try await fetchQuantitySamples(
// identifier: .appleExerciseTime,
// dataType: .exercise,
// unit: .minute(),
// startDate: startDate,
// endDate: endDate
// )
}
func fetchStandData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await fetchQuantitySamples(
identifier: .appleStandTime,
dataType: .stand,
unit: .minute(),
startDate: startDate,
endDate: endDate
)
try await fetchDailyCumulativeSamples(identifier: .appleStandTime, dataType: .stand, unit: .second(), startDate: startDate, endDate: endDate)
// try await fetchQuantitySamples(
// identifier: .appleStandTime,
// dataType: .stand,
// unit: .minute(),
// startDate: startDate,
// endDate: endDate
// )
}
func fetchStepCountData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await fetchDailyCumulativeSamples(
try await fetchDailyCumulativeSamples(
identifier: .stepCount,
dataType: .steps,
unit: .count(),
... ... @@ -336,6 +339,7 @@ final class HealthDataReader {
guard let type = NativeHealthTypeCatalog.quantity(identifier) else {
throw NativeHealthKitError.invalidType(identifier.rawValue)
}
let predicate = HKQuery.predicateForSamples(
withStart: startDate,
end: endDate,
... ...
... ... @@ -143,20 +143,7 @@ final class HealthKitService {
}
func refreshSharedWatchValues() async {
do {
if let hrv = try await reader.fetchLatestHRV() {
AppGroupConstants.defaults?.set(hrv, forKey: AppGroupConstants.Key.latestHRV)
}
} catch {
// Keep the previous widget value when a single read fails.
}
do {
let steps = try await reader.fetchTodayStepCount()
AppGroupConstants.defaults?.set(steps, forKey: AppGroupConstants.Key.latestStepCount)
} catch {
// Keep the previous widget value when a single read fails.
}
_ = WatchConnectivityService.shared.sendCommandMessage(AppGroupMessageKey.statusPulseRefresh)
}
func fetchHrvData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
... ...
... ... @@ -58,7 +58,7 @@ final class NativeHealthDataUploader {
var sleepUploadSuccess = true
var errorMessages: [String] = []
debugLog("uploadAll started, userId=\(AppShared.shared.userId ?? "<nil>")")
debugLog("uploadAll started ")
do {
let uploadTimeList = try await processLastUploadTime()
... ... @@ -512,10 +512,7 @@ struct NativeHealthUploadTimeRecorder {
}
private static func cacheKeyForCurrentUser() -> String {
let userId = AppShared.shared.userId
?? AppShared.shared.userSummary?.meUserInfo?.id.map(String.init)
?? AppGroupConstants.defaults?.string(forKey: AppGroupConstants.Key.userId)
?? ""
let userId = "\(AppShared.shared.userId ?? 0)"
return cacheKey + userId
}
}
... ...
... ... @@ -54,7 +54,7 @@ final class PlatformHostApiImpl: PlatformHostApi {
return false
#endif
}
func nativeHandleUrl(urlString: String) throws -> Bool {
if let url = URL(string: urlString){
UIApplication.shared.open(url)
... ... @@ -62,7 +62,7 @@ final class PlatformHostApiImpl: PlatformHostApi {
}
return false
}
func requestUnhandedUrl() throws -> String? {
let unhandedUrl = AppShared.shared.unhandedUrl
AppShared.shared.unhandedUrl = nil
... ... @@ -124,26 +124,23 @@ final class PlatformHostApiImpl: PlatformHostApi {
// 登录
func updateLoginInfo(jsonString: String, baseUrl: String) throws {
AppShared.shared.baseUrl = baseUrl
if let data = jsonString.data(using: .utf8){
do{
let model = try JSONDecoder().decode(FlutterUserSummary.self, from: data)
AppShared.shared.userSummary = model
AppGroupConstants.defaults?.set(baseUrl, forKey: AppGroupConstants.Key.baseUrl)
if let userId = model.meUserInfo?.id.map(String.init), !userId.isEmpty {
AppGroupConstants.defaults?.set(userId, forKey: AppGroupConstants.Key.userId)
AppShared.shared.userId = userId
}
if let token = model.accessToken{
AppGroupConstants.defaults?.set(token, forKey: AppGroupConstants.Key.token)
// 刷新用户信息
_ = WatchConnectivityService.shared.sendTextMessage(AppGroupMessageKey.login)
let watchUser = UserInfoModel(userId: model.meUserInfo?.id, token: token, baseUrl: baseUrl)
do{
let data = try JSONEncoder().encode(watchUser)
AppGroupConstants.defaults?.set(data, forKey: AppGroupConstants.Key.myUserInfo)
AppShared.shared.login(userInfo: watchUser)
_ = WatchConnectivityService.shared.sendLoginInfoMessage(userInfo: watchUser)
}catch{}
Task{
await AppShared.shared.reportDeviceInfo()
}
AppShared.shared.token = token
}
}catch{
DebugLogger.log(desc: error.localizedDescription)
... ... @@ -151,68 +148,24 @@ final class PlatformHostApiImpl: PlatformHostApi {
}
}
private static func extractUserId(from data: Data) -> String? {
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return nil
}
if let userId = stringify(json["userId"]) ?? stringify(json["user_id"]) {
return userId
}
if let meUserInfo = json["me_user_info"] as? [String: Any] {
return stringify(meUserInfo["id"]) ?? stringify(meUserInfo["userId"]) ?? stringify(meUserInfo["user_id"])
}
return nil
}
private static func stringify(_ value: Any?) -> String? {
switch value {
case let value as String:
return value
case let value as Int:
return String(value)
case let value as Int64:
return String(value)
case let value as NSNumber:
return value.stringValue
default:
return nil
}
}
// 退出登录
func logout() throws {
// 清除所有数据
AppGroupConstants.defaults?.dictionaryRepresentation().keys.forEach({
AppGroupConstants.defaults?.removeObject(forKey: $0)
})
AppShared.shared.logout()
_ = WatchConnectivityService.shared.sendTextMessage(AppGroupMessageKey.logout)
_ = WatchConnectivityService.shared.sendLoginInfoMessage(userInfo: nil)
}
// 刷新会员
func refreshVip() throws {
_ = WatchConnectivityService.shared.sendTextMessage(AppGroupMessageKey.reloadVip)
_ = WatchConnectivityService.shared.sendCommandMessage(AppGroupMessageKey.reloadVip)
}
// 刷新watch app 和表盘
func refreshWatchAppAndWidgets() throws {
_ = WatchConnectivityService.shared.sendTextMessage(AppGroupMessageKey.reloadAll)
_ = WatchConnectivityService.shared.sendCommandMessage(AppGroupMessageKey.reloadAll)
}
// 设置/移除 好友显示到表盘
func updateWatchOtherUserInfo(otherInfo: WatchAppOtherInfo?) throws {
defer{
try? refreshWatchAppAndWidgets()
}
guard let otherInfo else{
AppGroupConstants.defaults?.removeObject(forKey: AppGroupConstants.Key.showOtherUserInfo)
return
}
do{
let data = try JSONSerialization.data(withJSONObject: otherInfo.toParams())
AppGroupConstants.defaults?.set(data, forKey: AppGroupConstants.Key.showOtherUserInfo)
try refreshWatchAppAndWidgets()
}catch{
}
... ...
... ... @@ -37,7 +37,7 @@ final class WearEngineHostApiImpl: WearEngineHostApi {
}
func sendWatchSyncPayload(jsonPayload: String) throws -> Bool {
WatchConnectivityService.shared.sendWatchThemeChangedMessage()
WatchConnectivityService.shared.sendWatchThemeChangedMessage(json: jsonPayload)
}
func removeBackground(originImagePath: String, completion: @escaping (Result<String?, any Error>) -> Void) {
... ...
... ... @@ -6,48 +6,74 @@ enum AppGroupConstants {
static let identifier = "group.com.luiz.doublefeel.watchkitapp"
enum Key {
static let deviceInfo = "deviceInfo"
static let appDeviceToken = "appDeviceToken"
static let watchDeviceToken = "watchDeviceToken"
static let deviceInfo = "deviceInfo"
static let appDeviceToken = "appDeviceToken"
static let watchDeviceToken = "watchDeviceToken"
static let latestHealthData = "latestHealthData"
static let acitivyTarget = "acitivyTarget"
static let latestHRV = "latestHRV"
static let latestHRVBaseline = "latestHRVBaseline"
static let latestStepCount = "latestStepCount"
static let myWatchTheme = "myWatchTheme"
static let otherWatchTheme = "otherWatchTheme"
static let myTodayStandTime = "myTodayStandTime"
static let myTodayExerciseTime = "myTodayExerciseTime"
static let myTodayActiveEnergy = "myTodayActiveEnergy"
static let myTodayStepCount = "myTodayStepCount"
static let myLatestHeartRate = "myLatestHeartRate"
static let myTodayExerciseTime = "myTodayExerciseTime"
static let myTodayActiveEnergy = "myTodayActiveEnergy"
static let myTodayStepCount = "myTodayStepCount"
static let myLatestHeartRate = "myLatestHeartRate"
static let myUserCharacter = "myUserCharacter"
static let myUserInfo = "myUserInfo"
static let baseUrl = "baseURL"
static let userId = "userId"
static let token = "accessToken"
/// flutter登录信息
static let userSummary = "flutterUserSummary"
/// 显示好友信息
static let showOtherUserInfo = "showOtherUserInfo"
static let vipInfo = "vipInfo"
static let showRealtimeHRV = "showRealtimeHRV"
/// 会员信息
static let vipInfo = "vipInfo"
static let showRealtimeHRV = "showRealtimeHRV"
}
static var defaults: UserDefaults? {
UserDefaults(suiteName: identifier)
}
static func clearAllData(){
defaults?.removePersistentDomain(forName: identifier)
defaults?.synchronize()
}
static func clearUserSessionData() {
[
Key.latestHealthData,
Key.acitivyTarget,
Key.myWatchTheme,
Key.otherWatchTheme,
Key.myTodayStandTime,
Key.myTodayExerciseTime,
Key.myTodayActiveEnergy,
Key.myTodayStepCount,
Key.myLatestHeartRate,
Key.myUserInfo,
Key.userSummary,
Key.showOtherUserInfo,
Key.vipInfo,
Key.showRealtimeHRV
].forEach { key in
defaults?.removeObject(forKey: key)
}
defaults?.synchronize()
}
}
struct AppGroupMessageKey {
static let login = "login"
static let logout = "logout"
static let reloadAll = "reloadAll"
static let reloadVip = "reloadVip"
static let reloadTheme = "reloadTheme"
static let statusPulseRefresh = "statusPulseRefresh"
static let watchDeviceToken = "watchDeviceToken"
struct AppGroupMessageKey{
static let login = "login"
static let logout = "logout"
static let requestLoginState = "requestLoginState"
static let reloadAll = "reloadAll"
static let reloadVip = "reloadVip"
static let reloadTheme = "reloadTheme"
// 手表通知app刷新连接状态
static let statusPulseRefresh = "statusPulseRefresh"
static let watchDeviceToken = "watchDeviceToken"
}
... ...
... ... @@ -11,43 +11,60 @@ let kAppId = "6747254434"
class AppShared{
static let shared = AppShared()
var isLogin: Bool{
baseUrl.hasPrefix("http") && (userSummary?.accessToken?.count ?? 0 > 0)
baseUrl.hasPrefix("http") && (token?.count ?? 0 > 0)
}
private(set) var agent = UserAgent()
private(set) var payment = ApplePayment()
var baseUrl: String = "https://api.doublefeel.cn"
var token: String?
var userId: String?
var userSummary: FlutterUserSummary?
var baseUrl: String{
myUserInfo?.baseUrl ?? "https://api.doublefeel.cn"
}
var token: String?{
myUserInfo?.token
}
var userId: Int?{
myUserInfo?.userId
}
private(set) var myUserInfo: UserInfoModel?{
didSet{
WatchConnectivityService.shared.transferLoginInfo(userInfo: myUserInfo)
}
}
/// 冷启动待处理的urlstring
var unhandedUrl: String?
private init(){
login()
login(userInfo: nil)
}
func login(){
token = AppGroupConstants.defaults?.string(forKey: AppGroupConstants.Key.token)
userId = AppGroupConstants.defaults?.string(forKey: AppGroupConstants.Key.userId)
if let url = AppGroupConstants.defaults?.string(forKey: AppGroupConstants.Key.baseUrl){
baseUrl = url
func login(userInfo: UserInfoModel?){
if let userInfo{
myUserInfo = userInfo
return
}
guard let data = AppGroupConstants.defaults?.data(forKey: AppGroupConstants.Key.myUserInfo) else{
return
}
do{
myUserInfo = try JSONDecoder().decode(UserInfoModel.self, from: data)
}catch{
}
}
func logout(){
token = nil
userId = nil
userSummary = nil
myUserInfo = nil
AppGroupConstants.defaults?.removeObject(forKey: AppGroupConstants.Key.myUserInfo)
}
func reportDeviceInfo() async{
guard AppShared.shared.isLogin else {
print("not login")
print("reportDeviceInfo not login")
return
}
... ... @@ -56,7 +73,7 @@ class AppShared{
print("error invalid baseUrl \(AppShared.shared.baseUrl)")
return
}
/// 推送平台 choices: [(1, '小米'), (2, '华为'), (3, 'oppo'), (4, 'vivo'), (5, '荣耀'), (100, '苹果')]
var params: [String: String] = ["push_platform": "100"]
params["device_info"] = AppShared.shared.agent.deviceInfo
params["device_token"] = AppGroupConstants.defaults?.string(forKey: AppGroupConstants.Key.appDeviceToken)
... ... @@ -79,8 +96,13 @@ class AppShared{
let bodyText = String(data: data, encoding: .utf8) ?? ""
print("upload device info status=\(httpResponse.statusCode), body=\(bodyText)")
guard (200..<300).contains(httpResponse.statusCode) else {
return
}
} catch {
print("upload device info failed: \(error.localizedDescription)")
}
}
}
... ...
... ... @@ -197,18 +197,18 @@ class ApplePayment {
}
var params: [String: String] = [
"productId": productId,
"appAccountToken": appAccountToken
"product_id": productId,
"app_account_token": appAccountToken
]
params["originalTransactionId"] = originalTransactionId
params["transactionId"] = transactionId
params["original_transaction_id"] = originalTransactionId
params["transaction_id"] = transactionId
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(AppShared.shared.userSummary?.accessToken, forHTTPHeaderField: "access_token")
request.setValue(AppShared.shared.token, forHTTPHeaderField: "access_token")
request.setValue(AppShared.shared.agent.finalUA, forHTTPHeaderField: "User-Agent")
do {
... ... @@ -249,7 +249,7 @@ class ApplePayment {
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(AppShared.shared.userSummary?.accessToken, forHTTPHeaderField: "access_token")
request.setValue(AppShared.shared.token, forHTTPHeaderField: "access_token")
request.setValue(AppShared.shared.agent.finalUA, forHTTPHeaderField: "User-Agent")
do {
... ... @@ -343,8 +343,8 @@ extension ApplePayment {
return Task.detached {
for await result in Transaction.updates {
do {
let transaction = try await self.checkVerified(result)
if await AppShared.shared.isLogin{
let transaction = try self.checkVerified(result)
if AppShared.shared.isLogin{
let success = await self.verifyWithServer(appAccountToken: transaction.appAccountToken?.uuidString ?? "", originalTransactionId: String(transaction.originalID), transactionId: String(transaction.id), productId: transaction.productID)
// 更新客户产品状态
if success{
... ...
... ... @@ -6,7 +6,6 @@
//
import Foundation
import UIKit
import WebKit
extension UIApplication {
... ... @@ -40,10 +39,10 @@ class UserAgent {
func customUA() -> String {
let version = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) as! NSString
let bundle = Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? ""
let hardware = Self.hardwareString()
let hardware = hardwareString()
deviceInfo = hardware
AppGroupConstants.defaults?.set(hardware, forKey: AppGroupConstants.Key.deviceInfo)
let systemVersion = UIDevice.current.systemVersion
let height = UIApplication.shared.currentScreen?.bounds.height ?? 0
let width = UIApplication.shared.currentScreen?.bounds.width ?? 0
... ... @@ -55,7 +54,7 @@ class UserAgent {
return ua
}
private static func hardwareString() -> String {
private func hardwareString() -> String {
var systemInfo = utsname()
uname(&systemInfo)
... ...
//
// UserInfoModel.swift
// hippo
//
// Created by 权海 on 2026/6/26.
//
import Foundation
struct UserInfoModel: Codable, Equatable{
var userId: Int?
var token: String?
var baseUrl: String?
init(userId: Int? = nil, token: String? = nil, baseUrl: String? = nil) {
self.userId = userId
self.token = token
self.baseUrl = baseUrl
}
func toJson() -> [String: Any]{
do{
let data = try JSONEncoder().encode(self)
return try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as! [String : Any]
}catch{
return [:]
}
}
var jsonString: String? {
guard let data = try? JSONEncoder().encode(self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
}
... ...
... ... @@ -20,7 +20,9 @@ final class WatchConnectivityService: NSObject {
guard WCSession.isSupported() else { return false }
let session = WCSession.default
session.delegate = self
session.activate()
if session.activationState == .notActivated {
session.activate()
}
refreshState()
return true
}
... ... @@ -55,72 +57,62 @@ final class WatchConnectivityService: NSObject {
)
}
func sendTextMessage(_ message: String) -> Bool {
activate()
guard WCSession.default.isReachable else { return false }
WCSession.default.sendMessage(["message": message], replyHandler: nil) { error in
print("Watch message failed: \(error.localizedDescription)")
func transferLoginInfo(userInfo: UserInfoModel?){
guard activate() else { return }
let params = loginPayload(userInfo: userInfo)
do{
try WCSession.default.updateApplicationContext(params)
print("Send Watch updateApplicationContext: \(params)")
}catch{
print("Error Send Watch updateApplicationContext: \(params)")
}
}
return true
}
func sendCommandMessage(_ message: String) -> Bool {
activate()
guard WCSession.default.isReachable else { return false }
WCSession.default.sendMessage(["command": message], replyHandler: nil) { error in
print("Watch message send failed: \(error.localizedDescription)")
}
return true
}
func sendLoginInfoMessage(userInfo: UserInfoModel?) -> Bool {
guard let userInfo else {
return sendCommandMessage(AppGroupMessageKey.logout)
}
func syncPayload(jsonPayload: String) -> Bool {
activate()
guard let data = jsonPayload.data(using: .utf8),
let object = try? JSONSerialization.jsonObject(with: data),
let payload = object as? [String: Any] else {
return false
guard let json = userInfo.jsonString else {
return false
}
return sendCommandMessage(AppGroupMessageKey.login, json: json)
}
persistThemeIfPresent(payload: payload, originalJSON: jsonPayload)
guard WCSession.isSupported(), WCSession.default.isPaired, WCSession.default.isWatchAppInstalled else {
return false
private func loginPayload(userInfo: UserInfoModel?) -> [String: Any] {
guard var params = userInfo?.toJson(), !params.isEmpty else {
return ["command": AppGroupMessageKey.logout]
}
params["command"] = AppGroupMessageKey.login
return params
}
WCSession.default.transferUserInfo(payload)
try? WCSession.default.updateApplicationContext(payload)
sendWatchThemeChangedMessageIfNeeded(payload: payload)
func sendTextMessage(_ message: String) -> Bool {
activate()
guard WCSession.default.isReachable else { return false }
WCSession.default.sendMessage(["message": message], replyHandler: nil) { error in
print("Watch message failed: \(error.localizedDescription)")
}
return true
}
func sendWatchThemeChangedMessage() -> Bool {
sendCommandMessage(AppGroupMessageKey.reloadTheme)
}
func sendCommandMessage(_ message: String, json: String? = nil) -> Bool {
activate()
guard WCSession.default.isReachable else { return false }
var params: [String: Any] = [
"command": message
]
params["json"] = json
private func sendWatchThemeChangedMessageIfNeeded(payload: [String: Any]) {
if payload["myWatchTheme"] != nil || payload["watchTheme"] != nil || payload["theme"] != nil {
sendWatchThemeChangedMessage()
}
}
private func persistThemeIfPresent(payload: [String: Any], originalJSON: String) {
if let theme = payload["myWatchTheme"] as? String {
WatchThemeStore.shared.saveThemeJSONString(theme)
return
WCSession.default.sendMessage(params, replyHandler: nil) { error in
print("Watch message send failed: \(error.localizedDescription)")
}
return true
}
let themeObject = payload["watchTheme"] ?? payload["theme"]
guard let themeObject,
JSONSerialization.isValidJSONObject(themeObject),
let data = try? JSONSerialization.data(withJSONObject: themeObject),
let json = String(data: data, encoding: .utf8) else {
if payload["isWatchTheme"] as? Bool == true {
WatchThemeStore.shared.saveThemeJSONString(originalJSON)
}
return
func sendWatchThemeChangedMessage(json: String) -> Bool{
sendCommandMessage(AppGroupMessageKey.reloadTheme, json: json)
}
WatchThemeStore.shared.saveThemeJSONString(json)
}
}
extension WatchConnectivityService: WCSessionDelegate {
... ... @@ -132,6 +124,8 @@ extension WatchConnectivityService: WCSessionDelegate {
refreshState()
if let error {
print("WatchConnectivity activation failed: \(error.localizedDescription)")
}else{
transferLoginInfo(userInfo: AppShared.shared.myUserInfo)
}
}
... ... @@ -146,12 +140,17 @@ extension WatchConnectivityService: WCSessionDelegate {
func sessionReachabilityDidChange(_ session: WCSession) {
refreshState()
if session.isReachable {
_ = sendLoginInfoMessage(userInfo: AppShared.shared.myUserInfo)
}
}
func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
if message["command"] as? String == "statusPulseRefresh" {
if message["command"] as? String == AppGroupMessageKey.watchDeviceToken,
let token = message["token"] as? String {
AppGroupConstants.defaults?.set(token, forKey: AppGroupConstants.Key.watchDeviceToken)
Task {
await HealthKitService.shared.refreshSharedWatchValues()
await AppShared.shared.reportDeviceInfo()
}
}
}
... ... @@ -161,11 +160,22 @@ extension WatchConnectivityService: WCSessionDelegate {
didReceiveMessage message: [String: Any],
replyHandler: @escaping ([String: Any]) -> Void
) {
if message["command"] as? String == "statusPulseRefresh" {
if message["command"] as? String == AppGroupMessageKey.requestLoginState {
let userInfo = AppShared.shared.myUserInfo
var reply = loginPayload(userInfo: userInfo)
if let userInfo, let json = userInfo.jsonString {
reply["json"] = json
}
replyHandler(reply)
} else if message["command"] as? String == AppGroupMessageKey.watchDeviceToken,
let token = message["token"] as? String {
AppGroupConstants.defaults?.set(token, forKey: AppGroupConstants.Key.watchDeviceToken)
Task {
await HealthKitService.shared.refreshSharedWatchValues()
replyHandler(["success": true])
await AppShared.shared.reportDeviceInfo()
}
replyHandler(["success": true])
} else if message["command"] as? String == AppGroupMessageKey.statusPulseRefresh {
replyHandler(["success": true])
} else {
replyHandler(["success": true])
}
... ...