使用UserDefaults中的信息从多个ViewControllers更新Apple Watch

时间:2018-03-01 14:18:28

标签: ios swift delegates watchkit apple-watch

我有一个应用程序,用户可以在多个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()
    }
}

查看控制器1:

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!)
        }
    }
}

查看控制器2:

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!)
        }
    }
}

查看控制器3:

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!)
        }
    }
}

0 个答案:

没有答案