3

I have one button, one text box and one button in my iOS app. The user inputs text, presses the button and the user input is shown in the label. Also, the user input is saved when the app is closed and ran again by UserDefaults. The code for the iOS app is as follows:

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

}

But now, I want to access the data stored in the key myText in the WatchKit Extension and display the text in the WatchKit App. I have inserted a label in the WatchKit App but want the WatchKit Extension to access the data stored in 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)
    }

}

Can anyone please help me? I have read the documentations about App Groups on various sources, but the documentation is either of Swift v3.1 or Objective-C. Or any other solution except App Groups will work. Also, I want the data to be platform-independent. So, if the user inputs once in the iOS app and quits, I want the data to be accessible by the watch right away.

Thanks in advance... :)

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Pratham Patel
  • 67
  • 1
  • 11
  • Uh... No copyrights on the code – Pratham Patel Sep 13 '18 at 15:28
  • See my answer here: [Shared UserDefaults and App Extension](https://stackoverflow.com/questions/40065655/shared-userdefaults-between-app-and-extension-not-working-correctly/40068298#40068298) – zisoft Sep 18 '18 at 10:54
  • @zisoft that doesn't apply to watchOS extensions, since they are not regular app extensions. – Dávid Pásztor Sep 18 '18 at 11:08
  • Possible duplicate of [Retrieve user defaults information from an Apple Watch](https://stackoverflow.com/questions/44856215/retrieve-user-defaults-information-from-an-apple-watch) – Dávid Pásztor Sep 18 '18 at 11:08

0 Answers0