Saving Data In Swift [closed] - ios

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
In my application I created a structure with two properties:
struct questionCollection {
var question: String!
var answer: String!
}
I then created an instance of that:
questionCollections = [questionCollection(question: "What is 1+1?", answer: "2")]
Along with this I have a function that allows the user to add a question:
#IBAction func appendQuestion(sender: AnyObject) {
questionCollections += [questionCollection(question: questionInput.text, answer: answerInput.text)]
}
My question is what is the easiest way to save the user submitted data? I have only used NSUserDefaults before and I don't know what to do.
I really couldn't find any solution to my problem so if I could get some help that would be great. Thanks
To clarify: All I want to do is have the data stored so can be shown on a label and check to see if the correct answer is chosen. The data does not need to be seen by the user until it comes up in the label. I am also just creating a simple app so I only need this data to be saved on the device.
With what I am doing now I am not sure if I need to save my data but if someone can still answer this if they want for future reference.

Have you ever tried using Core Data before? It is Apple's default solution for persistent storage (saving things locally and having them appear again on every load of the app) . More information can be found here. https://developer.apple.com/library/watchos/documentation/Cocoa/Conceptual/CoreData/index.html

Currently, your structure can be represented as a dictionary value:
let dictionary:[String:String] = ["What is 1+1":"2", "What is 2+2": "4"]
and you can store a dictionary inside NSUserDefaults:
NSUserDefaults.standardUserDefaults().setObject(dictionary, forKey: "aKey")
I would say, this would be optimal solution in you case ...

Related

Loading of strings via AppStorage across classes in SwiftUI [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to save strings in SwiftUI via AppStrorage, this works so far, but I would also like to be able to access and load this saved data in another class.
If someone can help me, I would be very happy.
thanks
AppStorage uses UserDefaults behind the scenes. So you should be able to access the data directly in a non-SwiftUI context that way.
For instance, if you are using App Storage to store a Bool if the user has performed some activity, these two should be identical.
struct YourView: View {
#AppStorage("UserHasOnboarded") var hasOnboarded: Bool
// View stuff
}
class SomeClass {
func checkOnboarding() {
let hasOnboarded = UserDefaults.standard.bool(forKey: "UserHasOnboarded")
// Do your stuff
}
}
When you use the #AppStorage wrapper, you can pass in the UserDefaults store to use. So if you're wanting to use one shared among an app group, for instance, you can pass that in when you create the wrapper, and then use that same group instance in your class, and you'd be able to access data in your app as well as your app extensions.
Just use wrapper with same key, it is just reference to same UserDefaults storage
struct OneFileView: View {
#AppStorage("someKey") var someKey: String
// ... other code
}
struct AnotherFileView: View {
#AppStorage("someKey") var someKey: String
// ... other code
}

How to store an updated set of questions and answers in iOS/Swift and persist it

I'm starting a relatively simple app which presents a series of multiple choice questions. There will be 4 possible answers (A/B/C/D) and more than one choice can be correct. While manipulating such an object (one instance of a question with its accompanying answers) I've created the following data structure:
public class QAData {
var questionText: String
var answers: [String] // Will contain 4 separate answer options
var correct: [Bool] // contains 4 boolean values to match against options of answers to record correct answer/s
var selected: [Bool] // Will be updated to true if user selects relevant answer option
}
My question is what is the best way to store all the questions and answers in my app which also allows me to update the 'selected' attribute and store it across app launches? I'll initially have 100 questions however this could increase over time up to 1000.
Options I've considered is having an array containing all the data which is saved to user defaults - perhaps not really what it's designed for?
Persisting the object using NSCoding?
Or having the data in a SQLite database?
Any recommendations?
I guess saving of large amount of data in UserDefault is not a good way. It will badly affect to your application performance later on as your number of question might be increase.
I think coredata framework suit to your requirement . You can manage one entity in coredata which will persist all your questions with its four options, its boolean answers and user's selected answers. And you can easily save,update and retrieve data from local database using coredata.
You can save data in .Plist File or CoreData/Sqlite database. If all Q/A are static then prefer .plist file is better way.
If the Q&A are more less static and get only updated by you, store them in an asset (e.g in an HTML file) and read this file to access them.

How to save data of a game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to make a simple game for IOS using xcode and swift 2. The game I would like to make is similar to "a dark room", so it does not have complicated graphic or anything really difficult.
I was not able to find \ understand how to save (and then load) the data of the progress of the game, which would include my clickcounts, arrays, textview, and some variables for the inventory. I would like to have a button "save" and a button "load".
I would also like to add that the game I am making is with the setting "simple view application" of xcode.
I am new to programming, please be detailed :)
For a basic game you might get away with NSUserDefaults. Just create a plist file (i.e. Defaults.plist) with your settings - i.e. score, rounds, etc. and then use something like the code below to read register these defaults in your didFinishLaunchingWithOptions method in your AppDelegate.
let defaults = NSUserDefaults.standardUserDefaults()
let prefs = NSBundle.mainBundle().pathForResource("Defaults", ofType: "plist")
let dict = NSDictionary(contentsOfFile: prefs!)
defaults.setObject(dict, forKey: "defaults")
defaults.registerDefaults(dict as! [String : AnyObject])
defaults.synchronize()
Later you can read and set your defaults throughout your app by accessing:
NSUserDefaults.standardUserDefaults()
You would retrieve a value like so:
let score = NSUserDefaults.standardUserDefaults().integerForKey("score")
and set it this way:
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "score")

Best way to handle temporary value in swift using coredata [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying figure out what would be the best option to save some info into cache. I want it to be in there until notification pops out and button is pressed. I am already done everything else but I do not know what is the best solution for handling temporary values in cache. I need to use them even if app is closed. Is CoreData the best solution with NSUserDefaults? Lets assume that I have an array: var myArray = []
and I have textField. Now I want that texField input to be in array and if notification category button is pressed it deletes the first array item from the myArray. I need all this even if app is closed. Faulty code is inside "**".
Edit: The main problem is that how can delete every time the last value from array? It is not working if app is closed but works if it is opened.
This is what i've done so far.
This is whre I call out notification and it's action:
This is my array: var myArray = [String]()
Here I add object into array:
And now if notification is fired and button is pressed I would like to fire this function to delete first object from array:
You can use NSUserDefaults. They are accessable if the app is closed or open.
Read more about NSUserDefaults Here
Saving Example:
NSUserDefaults.standardUserDefaults().setObject(nameField.text!, forKey: "name")
Retrieving Example
Best Practice
if let predicate = NSUserDefaults.standardUserDefaults().objectForKey("name") {
//NSUserDefaults has a value
} else {
//NSUserDefaults does not has a value
}

Keep the reference of a programatically taken screenshot of current view in iOS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have wrote code for taking the screenshot of the current view.Now I have to keep a reference of it,for future use.And I dont want to store the image in device album.I have to store it in dictionary as a parameter.is it possible?How to do it.Please help..
It depends on what future use means. If you need to save it to disk, then you can use the UIImagePNGRepresentation(screenshot) and then save it with writeToFile(destinationPath, atomically: true), which wont need a dictionary as you can then load it back into an image using imageWithContentOfFile()
If you just need to store the UIImage inside a dictionary in memory for later use, then you can do this
let imageDictionary: [String: UIImage] = ["screenshot" : screenshot]
Get the image as a PNG using UIImagePNGRepresentation(myImage). This is a NSData object which you can store in a dictionary/plist or write directly into your library directory.
If you just want to hold it in memory, you need to save it in s variable with persistent scope. (That is, owned by something that sticks around.) If you have a VC (view controller) that's always around, you could add a property for your image to that VC.

Resources