在WatchKit应用和WatchKit扩展中访问iOS的UserDefaults值

时间:2018-09-13 15:27:18

标签: ios swift watchkit apple-watch

我的iOS应用中有一个按钮,一个文本框和一个按钮。用户输入文本,按下按钮,用户输入将显示在标签中。此外,当应用程序关闭并由UserDefaults再次运行时,用户输入将被保存。 iOS应用的代码如下:

import UIKit

class ViewController: UIViewController {

    // Connecting the front-end UI elements to the code
    @IBOutlet weak var myTextField: UITextField!
    @IBOutlet weak var myLabel: UILabel!

    // Connecting the button to the code
    @IBAction func myButton(_ sender: Any) {
        UserDefaults.standard.set(myTextField.text, forKey: "myText")
        myLabel.text = UserDefaults.standard.object(forKey: "myText") as? String
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // If there is any value stored previously, the stored data will be shown in the label and the text box to edit.
        if (UserDefaults.standard.object(forKey: "myText") as? String) != nil {
            UserDefaults.standard.set(myTextField.text, forKey: "myText")
            myLabel.text = UserDefaults.standard.object(forKey: "myText") as? String
        }
    }

}

但是现在,我想访问WatchKit扩展项中的键myText中存储的数据,并在WatchKit App中显示文本。我在WatchKit应用程序中插入了标签,但希望WatchKit扩展程序访问存储在UserDefaults.standard.object(forKey: "myText")中的数据。

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

    // Connecting the label to the code
    @IBOutlet var watchKitLabel: WKInterfaceLabel!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        watchKitLabel.setText((UserDefaults.standard.object(forKey: "myText")) as? String)
    }

}

有人可以帮助我吗?我已经从各种来源阅读了有关应用程序组的文档,但是该文档是Swift v3.1或Objective-C。或除应用程序组以外的任何其他解决方案都可以使用。另外,我希望数据与平台无关。因此,如果用户在iOS应用中输入一次并退出,我希望手表可以立即访问数据。

预先感谢...:)

0 个答案:

没有答案
相关问题