Swift Passing array of dictionary to NSMutableArray - ios

I am trying to pass swift array of dictionaries to the NSMutableArray. But I am getting error "Cannot convert value of type [[String : Anyobject?]] to expected argument type NSMutableArray". Below is the code:
var ary : [[String:AnyObject?]] = []
var mutableDictionary = [String: AnyObject?]()
for c in buffer {
mutableDictionary.updateValue(c.Name, forKey: "name")
mutableDictionary.updateValue(c.Number, forKey: "phoneNumber")
mutableDictionary.updateValue(c.id, forKey: "id")
ary.append(mutableDictionary)
}
Now passing this "ary" to the Objective C method as a NSMutableArray!
Manager.sharedInstance().List(ary)

Replica of your issue:
var ary : [[String:AnyObject]] = []
var mutableDictionary = [String: AnyObject]()
var mutableArray:NSMutableArray!
for _ in 0...4 {
mutableDictionary.updateValue("adsf", forKey: "name")
mutableDictionary.updateValue("dsf", forKey: "phoneNumber")
mutableDictionary.updateValue("sdfd", forKey: "id")
ary.append(mutableDictionary)
}
mutableArray = NSMutableArray(array: ary)
Removing the optional did the trick!

// try like this
Manager.sharedInstance().List(NSMutableArray(array: ary as! NSArray))

Related

How to save and retrieve Array of Objects value from Dictionary in Swift iOS?

I am newly to Swift programming. I am developing an app where I have an array of Objects that I need to save it into one Dictionary, means for Dictionary 'Array of Objects' should be my Value and 'ID' should be my Key.
Here 2 elements contains in my Array, how can I save and retrieve from Dictionary using any unique Key. Please suggest me. Thank you!
You can do it by
var myDict = Dictionary<String, Any>()
myDict = ["myKey": myArrayObjectName as! VideoRangeInfo]
Now you can access you array by use "myKey" of dictionary like below,
print("My array = \(myDict["myKey"] as! VideoRangeInfo)")
UPDATED: I think your array is objective c NSMutableArray not swift Array so
var myDic = NSMutableDictionary()
myDic.setObject(myArrayObjectName, forKey: "myKey")
And
print("My array = \(myDic.object(forKey: "MyKey") as! VideoRangeInfo)")
One simple approach is:
struct VideoRangeInfo {
var name: String
}
var arrayVideoRange = [
VideoRangeInfo(name: "Name1"),
VideoRangeInfo(name: "Name2"),
VideoRangeInfo(name: "Name3")
]
var dictionary = [String: VideoRangeInfo]()
for obj in arrayVideoRange {
dictionary.updateValue(obj, forKey: obj.name)
}
print(dictionary["Name1"]!)
print(dictionary["Name2"]!)
print(dictionary["Name3"]!)
Saving
var dictionary = Int:String
dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 1)
dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 2)
Getting
let value1 = dictionary[1] as! VideoRangeInfo
let value2 = dictionary[2] as! VideoRangeInfo

Get dictionary from NSMutableArray of dictionary

I'm trying to get a NSMutableDictionary from a NSMutableArray.
I set my array this way:
let test : NSMutableDictionary = NSMutableDictionary()
test.setValue("Monday", forKey: "day")
test.setValue("7PM - 8PM", forKey: "hour")
self.availabilityArray.add(test)
let test1 : NSMutableDictionary = NSMutableDictionary()
test1.setValue("Saturday", forKey: "day")
test1.setValue("8PM - 10PM", forKey: "hour")
self.availabilityArray.add(test1)
let test2 : NSMutableDictionary = NSMutableDictionary()
test2.setValue("Sunday", forKey: "day")
test2.setValue("2PM - 8PM", forKey: "hour")
self.availabilityArray.add(test2)
And in another method I try to get the "day" and "hour" value to set them in a UILabel.
I've tried to do this :
let dico = self.availabilityArray[i] //i being the index of a loop, not important here
self.dayNameLabel.text = (dico as AnyObject).object(forKey:"day") // This line does not work, I want to do something like that.
So how can I get the content of my NSMutableArray for a precise index as a NSDictionary ?
Thanks.
Thanks to Larme I found the solution, I juste replace
self.dayNameLabel.text = (dico as AnyObject).object(forKey:"day")
With
self.dayNameLabel.text = (dico as! NSMutableDictionary).object(forKey:"day") as! String?
You should use swift 2 (or 3) objects.
declare your array like that :
var availabilityArray: [[String: String]] = []
then create your dictionaries :
var test: [String: String] = [:]
test["day"] = "Monday"
test["hour"] = "7PM - 8PM"
var test1: [String: String] = [:]
test1["day"] = "Saturday"
test1["hour"] = "8PM - 10PM"
var test2: [String: String] = [:]
test2["day"] = "Sunday"
test2["hour"] = "2PM - 8PM"
add them to the array :
self.availabilityArray.append(test)
self.availabilityArray.append(test1)
self.availabilityArray.append(test2)
and finally access the object :
let dico = self.availabilityArray[0]
self.dayNameLabel.text = dico["day"]
dico["day"] is optional, so use dico["day"]! or use a real unwrap with if let

How to store Array in NSUserDefault in Swift?

So I've been trying for a few hours for a way to store an array to NSUserDefault and print them to the cells but the data is not saving as an array, it basically only saves one value at a time.
var emailData = [String]()
var passwordData = [String]()
#IBAction func addPressed(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
emailData.append(addEmail.text!)
passwordData.append(addPassword.text!)
var storedEmail = defaults.objectForKey("emailData") as? [String] ?? [String]()
var storedPasswords = defaults.objectForKey("passwordData") as? [String] ?? [String]()
// then update whats in the `NSUserDefault`
defaults.setObject(emailData, forKey: "emailData")
defaults.setObject(passwordData, forKey: "passwordData")
// call this after you update
defaults.synchronize() /*
NSUserDefaults.standardUserDefaults().setValue(addEmail.text, forKey: "email")
NSUserDefaults.standardUserDefaults().synchronize()
*/
}
So basically the data is not saving.
You can store Array too, by this way
let userDefault = NSUserDefaults.standardUserDefaults()
let arr = ["abc","xyz","pqr"]
userDefault.setObject(arr, forKey: "arr")
userDefault.synchronize()
let data = userDefault.objectForKey("arr") as! [String]
Save the Swift Array in Swift.
let kUserDefault = NSUserDefaults.standardUserDefaults()
kUserDefault.setObject(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()
Get Array
1. arrayForKey : You getting Swift Array
kUserDefault.arrayForKey("nameArray")!
2. objectForKey : You getting NSArray
kUserDefault.objectForKey("nameArray")!
3. valueForKey : You getting NSArray
kUserDefault.valueForKey("nameArray")
It is possible to store arrays in NSUserDefaults. But separating email and password in separate array is not suitable. You should store it as one object since they are related.
In your case an array of Dictionary objects is better, which is possible to store in NSUserDefaults as well, which you can retrieve as an array of Dictionary.
Here is the sample:
let userDefault = NSUserDefaults.standardUserDefaults()
var storedCredentials = userDefault.objectForKey("credentials") as? [[String:AnyObject]] ?? [[String:AnyObject]]()
let email =
[
"email" : addEmail.text!,
"password": addPassword.text!
]
storedCredentials.append(email)
userDefault.setObject(storedCredentials, forKey: "credentials")
userDefault.synchronize()
You can't save an array of [String] in NSUserDefault, if you look at the documentation :
For NSArray and NSDictionary objects, their contents must be property
list objects.
So what you can do is convert your [String] into NSData then save it into NSUserDefault.
// Store it as NSData
var emailData = [String]()
emailData.append("email1")
emailData.append("email2")
let emailIntoNSData = NSKeyedArchiver.archivedDataWithRootObject(emailData)
NSUserDefaults.standardUserDefaults().setObject(emailIntoNSData, forKey: "emailData")
// Retrieve it :
let emailFromNSData = NSUserDefaults.standardUserDefaults().objectForKey("emailData") as? NSData
if let emailFromNSData = emailFromNSData {
let emailArray = NSKeyedUnarchiver.unarchiveObjectWithData(emailFromNSData) as? [String]
if let emailArray = emailArray {
NSLog("Email Data : \(emailArray)") // ["email1","email2"]
// do something…
}
}

Appending an Array in NSUserDefaults Swift

So I want to append an array in the NSUserDefaults, not save an entirely new one. The issue is that I want the array to be a logged history of a certain type of user interaction so I need to be appending an existing array in the NSUserDefaults, and not overwriting it.
i.e Not:
var data = [String]()
var questionsAsked = [String]()
func storeData() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(questionsAsked, forKey: "questionsAsked")
defaults.setObject(data, forKey: "data")
var storedQuestionsAsked = defaults.objectForKey("questionsAsked") as? [String] ?? [String]()
var storedData = defaults.objectForKey("data") as? [String] ?? [String]()
}
The array(s) are based in my Modal, and the appending is occurring by appending that array in the ViewController of that Modal
I tried just calling a function like this, but this is just calling an empty array because its never being re-saved to the NSUserDefaults:
func updateQuestionsAsked(questionAsked: String, answerGiven: String) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject([String](), forKey: "questionsAsked")
defaults.setObject([String](), forKey: "data")
var storedQuestionsAsked = defaults.objectForKey("questionsAsked") as? [String] ?? [String]()
var storedData = defaults.objectForKey("data") as? [String] ?? [String]()
storedData.append(questionAsked)
storedQuestionsAsked.append(answerGiven)
NSUserDefaults.standardUserDefaults().synchronize()
}
Is there some kind of synchronization thing I'm missing? I'm sure this is super simple but I'm just spacing out on what to do. Thanks!
YOu are setting empty data for keys "questionsAsked" & "data",
func updateQuestionsAsked(questionAsked: String, answerGiven: String) {
let defaults = NSUserDefaults.standardUserDefaults()
//remove this
//defaults.setObject([String](), forKey: "questionsAsked")
//defaults.setObject([String](), forKey: "data")
var storedQuestionsAsked = defaults.objectForKey("questionsAsked") as? [String] ?? [String]()
var storedData = defaults.objectForKey("data") as? [String] ?? [String]()
storedData.append(questionAsked)
storedQuestionsAsked.append(answerGiven)
// then update whats in the `NSUserDefault`
defaults.setObject(questionsAsked, forKey: "questionsAsked")
defaults.setObject(data, forKey: "data")
// call this after you update
defaults.synchronize()
}
Another is maybe you failed to set object here...
func storeData() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(questionsAsked, forKey: "questionsAsked")
defaults.setObject(data, forKey: "data")
// call this after setting Objects
//--
defaults.synchronize()
//--
...
}

objectForKey returns nil for NSUserDefaults in Swift

I am using the following code to set a value into NSUserDefaults using Swift. Here is my code:
let key = "ticker"
let currencyTickerData = [key:"USD"]
NSUserDefaults.standardUserDefaults().setObject(currencyTickerData, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
let tickerVal : [NSString]? = (NSUserDefaults.standardUserDefaults().objectForKey(key)) as? [NSString]
print(tickerVal)
For some reason, tickerVal is nil. Why is this? As far as I can tell, it should return "USD."
NSUserDefaults uses NSDictionary instead of Swift's dictionary type. You can explicitly type tickerVal as an NSDictionary like so:
let key = "ticker"
let currencyTickerData: NSDictionary = [key:"USD"]
NSUserDefaults.standardUserDefaults().setObject(currencyTickerData, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
let tickerVal = (NSUserDefaults.standardUserDefaults().objectForKey(key)) as NSDictionary
print("\(tickerVal)")
It is same code that will save you're date:
var myValue:NSString = "USD"
NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"ticker")
NSUserDefaults.standardUserDefaults().synchronize()
var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("ticker")
println(myOutput)

Resources