我有一个应用程序,用户可以在多个ViewControllers中更新相同的UserDefaults
键。我想要做的是每次在三个ViewControllers之一中更新信息时通知Apple Watch并使用新值更新它。
以下是我正在做的事情,我认为这不是最好的方法。正如您所看到的,我正在复制所有三个viewControllers中的代码。
从多个ViewControllers更新Apple Watch的最佳方法是什么?
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var canPurchase:Bool = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Instantiate singleton for sharing the WCSession between viewControllers
WatchSessionManager.sharedManager.startSession()
}
}
class ViewController1: UIViewController{
func upDateUserDefaults(){
/// Update UserDefaults...
sendInfoToAppleWatch()
}
func sendInfoToAppleWatch(){
/// Read UserDefaults
let message:String = UserDefaults.standard.string(forKey: "messageKey")!
/// Send message to Apple Watch with value from UserDefatults
let session = WatchSessionManager.sharedManager.session
if session.isWatchAppInstalled && session.isPaired{
WatchSessionManager.sharedManager.sendAgeToWatch(userMessage: message!)
}
}
}
class ViewController2: UIViewController{
func upDateUserDefaults(){
/// Update UserDefaults...
sendInfoToAppleWatch()
}
func sendInfoToAppleWatch(){
/// Read UserDefaults
let message:String = UserDefaults.standard.string(forKey: "messageKey")!
/// Send message to Apple Watch with value from UserDefatults
let session = WatchSessionManager.sharedManager.session
if session.isWatchAppInstalled && session.isPaired{
WatchSessionManager.sharedManager.sendAgeToWatch(userMessage: message!)
}
}
}
class ViewController3: UIViewController{
func upDateUserDefaults(){
/// Update UserDefaults...
sendInfoToAppleWatch()
}
func sendInfoToAppleWatch(){
/// Read UserDefaults
let message:String = UserDefaults.standard.string(forKey: "messageKey")!
/// Send message to Apple Watch with value from UserDefatults
let session = WatchSessionManager.sharedManager.session
if session.isWatchAppInstalled && session.isPaired{
WatchSessionManager.sharedManager.sendAgeToWatch(userMessage: message!)
}
}
}