Using NSUserDefaults to share data to watchkit - ios

I am trying to use NSUserDefaults to share my data with the WatchKit files. I am trying to have it so when the button function is executed the watchLabel.setText to data from an array. The array and function that selects the data was created in the iOS application. (Unfortunately many resources I come across are in objective-C or extremely vague.)
I have set up app groups for both iOS and Watchkit
In my iOS Swift file I am trying to share my array(arrayBook) and function(.randomData) to use with the WatchKit controller. PS: I have no compiler errors.
let sharedDefaults = NSUserDefaults(suiteName: "group.applewatchtest")
sharedDefaults?.arrayForKey(arrayBook.randomData())
sharedDefaults?.synchronize()
Watchkit Controller; Unsure the correct syntax for fetching data and setting the label to random string from the array. - This is within the UIButton func.
let sharedDefaults = NSUserDefaults(suiteName: "group.applewatchtest")
let sharedArray = sharedDefaults?.arrayForKey("Shared")
watchLabel.setText(arrayBook.randomData())
Where am I going wrong when fetching the data to set the label to data from the array which is stored in my iOS application.

sharedDefaults?.arrayForKey(arrayBook.randomData())
This line of code is not doing anything. You're reading the array from defaults, using a key of whatever arrayBook.randomData() returns, and doing nothing with it.
I assume you want something like
sharedDefaults?.setObject(arrayBook, forKey:"Shared")
Which will write that array into defaults. You then get it back out in the watch (which looks fine) and get a random value using randomData().

Related

Swift How to fix errors with Target Membership?

I am beginner to Swift and I am not aware of all the little details, so please forgive if it's a stupid question
My app is in quite advanced stage of development, so I would like to not mess with the existing code as little as possible. My problem is that I want to implement Today Extension in my app, in it I want to display a tableView that will display data from a single array from my "Plum" class and I need one method from the class to handle the selection. Unfortunately when I change the Plum's target membership to TodayExtension a whole bunch of errors are shown because many APIs from that class aren't available to TodayExtension. The class inherits from AVAudioPlayer so most essential methods aren't available in Extension.
I tried to create a helper class that would get the array from Plum and return it in method to my TableView but that still doesn't work because of "Use of unresolved identifier 'Plum'"
How can I obtain the array and use the method?
I think while adding Today Extension you might have got some classes for today extension,
You can use App Group with User Defaults functionality to transfer data from iOS app to today Extension classes
1) To set data you can use
var defaults: NSUserDefaults = NSUserDefaults(suiteName: <GroupID>)!
defaults.setObject(<YourArray, forKey:<KeyName>)
2) In Today Extension target's Class you can fetch that array like this
var defaults: NSUserDefaults = NSUserDefaults(suiteName: <GroupID>)!
var <YourArray> = defaults.stringForKey(<KeyName>)
Note : This is just pseudo code might contain error
Adding the Plum class in the today extension is a bad idea. Extensions should be lightweight and you only need to transfer the data needed.
In your case you may need the array of title and description. So form a array of dictionary with needed details and store these details in App group user defaults like #Hitesh answer.
In your today extension class, read this array from the user defaults then display the details in the table view.

How do I save a var when my iOS app closes? [duplicate]

This question already has answers here:
How to save local data in a Swift app?
(12 answers)
Closed 6 years ago.
In total I have 2 viewcontrolers. The App is the same like this guy made in a tutorial. https://www.youtube.com/watch?v=LrCqXmHenJY&t=40s
To make a start, I made a var:
import UIKit
var list = ["Task 1", "Task 2", "Task 3", "Task 4"]
class FirstViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{
My current problem is, that when I close the app no ToDo's which I created were saved.
What do I need to do to save my var list so that my ToDo-List isn't empty when I open it for the next time?
You can use UserDefaults to save/load application state or configurations. For complex requirements use CoreData
Writing/Saving before app termination
let defaults = UserDefaults.standard
defaults.set(true, forKey: "Enabled")
Reading/Loading on app launch
let defaults = UserDefaults.standard
let enabled = defaults.bool(forKey: "Enabled")
Read the related Apple docs here.
If you want an easy way to store a list of strings, you can use UserDefaults. Another way to do this is to use Core Data which is more difficult to use. It is usually used to store more complex data structures than an array of strings.
To save the string array to UserDefaults, do this:
UserDefaults.standard.set(list, "myStringArray")
You can replace "myStringArray" with any key you want.
To retrieve it, do this:
list = UserDefaults.standard.stringArray(forKey: "myStringArray")
I suggest you save the array in this method in App Delegate:
func applicationDidEnterBackground(_ application: UIApplication) {
}
For more info on User Defaults, see https://developer.apple.com/reference/foundation/userdefaults
You have very simple needs. Look at NSUserDefaults (now called UserDefaults in Swift 3.)
Save your data to UserDefaults when it changes, and read it back when you display your view controller.
As Eric says in his comments, make list an instance variable of your view controller.
EDIT:
In the comments below, rmaddy pointed out that the app will be saving a to-do list. That will likely grow in complexity from an array of a handful of items to a larger array or potentially a more complex structure.
Given that, you might want to look at saving your data to a plist file in the documents directory (quite simple) or using NSCoding if you have custom objects other than the small list of "property list" types that can be saved to a plist.
Both of those solutions read and write the data all at once to a file. That might be ok for a to-do list app.
If you need to change parts of a larger data-set and leave the rest unchanged then it's time to consider a database like Core Data.

Where do I store File Options in a Swift App? [duplicate]

This question already has answers here:
How to save local data in a Swift app?
(12 answers)
Closed 6 years ago.
I have a simple swift app that pulls JSON information from online and uses it in a table view. For example, a document would have a name, description, etc. As well as an url to display the pdf. I know how to open the PDF from both local storage and an online url, but if I had an "available offline" value that could be either true or false, where would I store it?
I cannot put it as a JSON key because then it would change the setting for all users accessing the online JSON files, so where do I put a simple device specific option such as this?
NsUserDefault is the best choice for you.
You have to store single variable so.
Coredata is used to small tiny database like if you want to store your data like name , description than you can use coreData.
Here you simple store with NSUserDefaults
Edited:-
To store:-
let value = NSUserDefaults.standardUserDefaults()
value.setInteger (10,forKey: "value")
// here you can use setBool setDouble etc.
To retrieve:-
let num = value.objectForKey ("value") as? Integer
NSUserDefaults is great for easy tiny-scale storage, like remembering settings.
It works like this:
[[NSUserDefaults standardUserDefaults] setObject:#"object" forKey:#"this is my key"];
Then, later,
[[NSUserDefaults standardUserDefaults] objectForKey:#"this is my key"];
//this gives you your object
You just have to be careful with typing, otherwise your app will crash.
Here's the docs for NSUserDefaults:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/

How to save entered data to make it available after app restart

I have my own custom data structures which receive input through the ViewController class. The interface is a simple text field, which is linked to a variable that the contents of the text field is copied to. Upon launching the app, the text field should be prepopulated with data entered in the past. However, as soon as I close the app, the data is lost. I am new to programming and assume this can be remedied by implementing the necessary functions in AppDelegate class, more specifically, under the default applicationWillTerminate function. If this is correct, how do I implement the data saving process? If not, where & how do I make sure data entered is stored so that fields are prepopulated the next time the app is opened?
If you need to store small amount of data, take a look at NSUserDefaults.
If your data better fits to a database, you can use SQLite (may be with a wrapper) or Core Data.
There is also a modern but not yet very mature cross-platform mobile database called Realm (partially open-sourced at the moment).
Since you are saving TextField data(which use mostly small string text) Use NSUserDefaults to store the string for persistence. What you need to do is at textFieldEndEditing save the text to NSUserDefaults and in viewDidLoad assign it to textField.
Saving To NSUserDefaults:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(myTextField.text, forKey: "TextFieldText")
defaults.synchronize()
Retrieving from NSUserDefaults:
let defaults = NSUserDefaults.standardUserDefaults()
if let savedText = defaults.stringForKey("TextFieldText")
{
print("Textfield Text: \(savedText)")
}

How to store form data in a swift app

I'm working on my first app and I need some help understanding what kind of data storage I need. I'm familiar with PHP, SQL, and databases but I don't know where to start with this project.
The app is pretty much a basic form with text fields, pickers, and uploaded images. At the end, the user will press submit and all of their data will be sent in an email.
What is the best way to store their data, so the user can go to previous screens and have their previously entered info still there. And then what is the best way to store the data after they press submit to send it in an email?,
Thanks so much for your help!
If it's just form data that you're storing once for submission, for simplicity sake, I recommend just stuffing it in a global dictionary that you can access from different views. Swift makes this easy by just adding an empty swift file and defining your dictionary at the top:
var myFormData: [String: AnyObject]()
You can now access "myFormData" form anywhere in your app, add and remove stuff from it.
You shouldn't technically need to "reload previous views" because of the way the navigation stack works. Anything you go back to should hold it's info.
If you really need to save the data to allow the user to close the app and then pick up where they left off much later, then I recommend simply kicking your dictionary to NSUserDefaults. It doesn't sound like something that needs to involve a database.
You can use a class called NSUserDefaults
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //make an instance
defaults.setObject("Bob", forKey: "myName") //storing a value
defaults.synchronize() //synchronize data
println(defaults.objectForKey("myName")!) //retrieve the data

Resources