Last active
February 24, 2023 05:51
-
-
Save AppleBetas/7c5d27a96d15da198a61ab9210d46aa6 to your computer and use it in GitHub Desktop.
WatchInfo.swift - Quickly get connected Apple Watch and installed Watch app state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// WatchInfo.swift | |
// | |
// Created by AppleBetas on 2016-12-10. | |
// Copyright © 2016 AppleBetas. All rights reserved. | |
// | |
import Foundation | |
import WatchConnectivity | |
class WatchInfo: NSObject, WCSessionDelegate { | |
private var session: WCSession? | |
weak var delegate: WatchInfoDelegate? | |
override init() { | |
super.init() | |
if WCSession.isSupported() { | |
session = WCSession.default() | |
} | |
oldAppState = _appState | |
session?.delegate = self | |
} | |
enum WatchAppState { | |
case unsupported, noWatch, notInstalled, installed | |
var description: String { | |
switch self { | |
case .unsupported: | |
return "This device does not support pairing with Apple Watch." | |
case .noWatch: | |
return "No Apple Watch is paired with iPhone." | |
case .notInstalled: | |
return "This app is not installed on the paired Apple Watch." | |
case .installed: | |
return "This app is installed on the paired Apple Watch." | |
} | |
} | |
} | |
// What state is the watch app in | |
var appState: WatchAppState { | |
let appState = _appState | |
oldAppState = appState | |
return appState | |
} | |
private var _appState: WatchAppState { | |
if let session = session { | |
if session.isPaired { | |
if session.isWatchAppInstalled { | |
return .installed | |
} | |
return .notInstalled | |
} | |
return .noWatch | |
} | |
return .unsupported | |
} | |
private var oldAppState: WatchAppState! | |
var complicationEnabled: Bool { | |
if appState == .installed { | |
return session?.isComplicationEnabled ?? false | |
} | |
return false | |
} | |
// MARK - Watch Session Delegate | |
func sessionWatchStateDidChange(_ session: WCSession) { | |
let currentState = _appState | |
if currentState != oldAppState { | |
// New app state | |
oldAppState = currentState | |
delegate?.watchAppStateChanged(to: _appState) | |
} | |
} | |
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {} | |
func sessionDidBecomeInactive(_ session: WCSession) {} | |
func sessionDidDeactivate(_ session: WCSession) {} | |
} | |
protocol WatchInfoDelegate: class { | |
func watchAppStateChanged(to watchAppState: WatchInfo.WatchAppState) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment