| 1 | // |
| 2 | // WatchOsDeviceManager.swift |
| 3 | // Runner |
| 4 | // |
| 5 | // Created by Gurpal Singh on 27/12/24. |
| 6 | // |
| 7 | |
| 8 | |
| 9 | import WatchConnectivity |
| 10 | |
| 11 | class WatchOsDeviceManager: |
| 12 | private let context: UIViewController |
| 13 | private static var sharedInstance: WatchOsDeviceManager? |
| 14 | private var session: WCSession? |
| 15 | |
| 16 | // Updated singleton accessor |
| 17 | static var shared: WatchOsDeviceManager { |
| 18 | guard let instance = sharedInstance else { |
| 19 | fatalError("WatchOsDeviceManager must be initialized before accessing shared instance") |
| 20 | } |
| 21 | return instance |
| 22 | } |
| 23 | |
| 24 | // Updated initializer method |
| 25 | static func initialize |
| 26 | if sharedInstance == nil { |
| 27 | sharedInstance = WatchOsDeviceManager(context: |
| 28 | } |
| 29 | return sharedInstance! |
| 30 | } |
| 31 | |
| 32 | private init(context: UIViewController |
| 33 | self.context = context |
| 34 | super.init() |
| 35 | if WCSession.isSupported() { |
| 36 | session = WCSession.default |
| 37 | session?.delegate = self |
| 38 | session?.activate() |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // WCSessionDelegate methods |
| 43 | func session(_ |
| 44 | DispatchQueue.main.async { |
| 45 | switch activationState { |
| 46 | case .activated: |
| 47 | print("WCSession activated successfully") |
| 48 | case .inactive: |
| 49 | print("WCSession is inactive") |
| 50 | case .notActivated: |
| 51 | print("WCSession could not be activated: \(error? |
| 52 | @unknown default: |
| 53 | print("Unknown activation state") |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | func sessionDidBecomeInactive(_ |
| 59 | print("WCSession became inactive") |
| 60 | } |
| 61 | |
| 62 | func sessionDidDeactivate(_ |
| 63 | WCSession.default.activate() |
| 64 | } |
| 65 | |
| 66 | // Get connected Watch devices |
| 67 | func getConnectedDevices() -> |
| 68 | guard let session = session, session.isPaired else { |
| 69 | return [] |
| 70 | } |
| 71 | |
| 72 | var devices: [[String: Any |
| 73 | |
| 74 | if session.isPaired && session.isWatchAppInstalled { |
| 75 | let device: [String: Any |
| 76 | "id": session.isPaired |
| 77 | "displayName": "Apple Watch", |
| 78 | "isNearby": session.isReachable |
| 79 | ] |
| 80 | devices.append(device) |
| 81 | } |
| 82 | |
| 83 | return devices |
| 84 | } |
| 85 | } |