I am using the excellent SwiftyUserDefaults, a wrapper for NSUserDefaults
with Swift to allow my app to persist a certain array of data, like so (lots of code removed to show just the important parts:
Working Code
import SwiftyUserDefaults //The following is to show implementation in the parent iOS app. It works fine.
class ViewController: UICollectionViewController {
var arrayToStore = DefaultsKey<NSArray>("arrayToStore")
override func viewDidLoad() {
Defaults[arrayToStore] = ["Element 1", "Element 2", "Element 3"]
}
func aFunctionThatNeedsToReadTheArray() {
print([Defaults[arrayToStore]])
}
}
Research
The above works fine, but I also want the watchKit watchOS 2 app of this parent app to be able to read arrayToStore.
I did a bit of research and learned that Apple offers a solution for this, App Groups, which enables things in NSUserDefaults and other data storage means to be available across apps - in this case, between a parent iOS app and its companion watchOS watchKit app. EDIT: I LEARNED THANKS TO @PETAHCHRISTIAN THAT APP GROUPS DOES NOT WORK FOR WATCHOS 2. SO, WHAT OTHER MEANS ARE THERE?
Edit 2: Knowing that App Groups is not the solution, I did a bit more research and have determined that a possible solution is theWatchConnectivity
framework. Is this correct, and if so, how can I use it to allow the watch app to have access to arrayToStore
?
Question
However, my question is: How do I do this with SwiftyUserDefaults
? I want to be able to have arrayToStore
, an array in the parent app, readable by the watchOS 2 app via app groups (or another means, if there is a better way NOTE: Thanks to @PetahChristian I have learned that App Groups is not the way to do this. As such, how can I obtain the desired result of the watch app reading an array from the parent app via other means?).
What I am trying:
- Enable app groups by, in "Capabilities" of the iOS app and watchKit app, turning on app groups and selecting the app group as shown in the answer here
- In the app extension for the watchKit app, using
print([Defaults[arrayToStore]])
, resulting in "Use of unresolved identifier arrayToStore". The expected result is printing "Element 1", "Element 2", "Element 3"