在Apple Watch Class

时间:2016-07-12 22:33:37

标签: swift apple-watch

如何在Apple Watch上存储数据?我曾尝试在我的应用程序中使用NSUserDefaults();但是,我了解到它停止了与Watch OS2一样的工作。我实现了Watch Connectivity,因为这似乎是新方法;但是,我无法将数据存储起来。我有一个标签,我通过我的iOS应用程序传递值,但当我强制关闭手表上的应用程序并再次启动它时,值被重置?我如何让它坚持下去?谢谢!

import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController, WCSessionDelegate {

@IBOutlet var balance: WKInterfaceLabel!

@IBOutlet var change: WKInterfaceLabel!

let session = WCSession.defaultSession()


override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    //Need to check if labels contain value already on startup
    processApplicationContext()

    session.delegate = self
    session.activateSession()
    // Configure interface objects here.
}

override func willActivate() {
    super.willActivate()

}

override func didDeactivate() {
    // This method is called when watch view controller is no longer visible
    super.didDeactivate()
}

func processApplicationContext() {
    if let iPhoneContext = session.receivedApplicationContext as? [String : String] {

        let value = iPhoneContext["amount"]

        if (value != nil) {
            let passedValues = value!.componentsSeparatedByString("&")
            balance.setText(passedValues[1])
            change.setText(passedValues[0])

            if passedValues[0].rangeOfString("+") != nil{
                change.setTextColor(UIColor.greenColor())
            } else {
                change.setTextColor(UIColor.redColor())
            }

        }
        /*else {
            balance.setText("$0.00")
            change.setText("0.00")
        }
         */

    }
}

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
    dispatch_async(dispatch_get_main_queue()) {
        self.processApplicationContext()
    }
}

我将收到的值分成两部分,因为我不知道如何通过监视连接传递多个值

0 个答案:

没有答案