I have array of user
var User:[User] = []
I want by alamofire and swiftyjson get info from http://jsonplaceholder.typicode.com/users
I know how to request and then i have array of json
how i can make loop through json array and create object of user then append in array User[]
I think my problem with loop , this is from swifty json page
for (index,subJson):(String, JSON) in json {
//Do something you want
}
how i can use it in my App?
You can use similar following code
for (_, subDataJSON): (String, JSON) in dataJSON {
let u = User()
u.name = subDataJSON["name"].stringValue
u.id = subDataJSON["id"].intValue
u.active = subDataJSON["active"].boolValue
self.User.append(u)
}
Parse your data json in loop then at the end of loop append single user object to global class User array like that.
Then use your class scoped User array like as you want.
Related
I have an array of classes, which looks like this:
var myItems = [myClass]()
class myClass: NSObject {
var a: String?
var b: String?
var c: String?
var d: String?
}
What I want is to save the array called myItems into my database, and have every class inside of a personal section inside the database. Basically, I want every class to look like the one called "Eko" in this image:
To clarify, after "Eko" all the rest of the classes which is inside of the array myItems should be displayed. To achieve what the picture is demonstrating, I used this code:
let data = self.myItems[0]
let currU = FIRAuth.auth()?.currentUser?.uid
let userRef = self.ref.child("users").child(currU!).child(data.a!)
userRef.updateChildValues(["a": data.a!, "b": data.b!, "c": data.c!, "d": data.d!])
Obviously, this will only save the class at index 0 from the array myItems into the Firebase Database, which is displayed in the image above.
My question is thus, how do I save the entire array into the database? With my code I can only save 1 class from the array, and I would like to save all of the items into the database, so that they end up looking the same way that the one class does in the image. You could compare this to populating a tableView, where you need the "indexPath.row" to populate it with all the items instead of only one. I hope that I was clear enough!
You can't save a class into Firebase. But.. A class has a similar structure to a dictionary (properties and values, like key: value pairs etc).
Arrays in Firebase should generally be avoided - they have limited functionality and the individual elements cannot be accessed and for any changes you have to re-write the entire array.
Using a structure where the parent key names are created with childByAutoId is usually preferred.
The easiest solution is to simply add intelligence to the class so it would craft a dictionary and then save itself.
Craft a user class
UserClass
var name = String()
var food = String()
func saveToFirebase() {
let usersRef = myFirebase.child(users)
let dict = ["name": self.myName, "food", self.myFood]
let thisUserRef = usersRef.childByAutoId()
thisUserRef.setValue(dict)
}
}
and and array to store them
var usersArray = [Users]()
populate the array
var aUser = UserClass()
aUser.name = "Leroy"
aUser.food = "Pizza"
usersArray.append(aUser)
var bUser = UserClass()
bUser.name = "Billy"
bUser.food = "Tacos"
usersArray.append(bUser)
and then iterate over the array saving each user
for user in usersArray {
user.saveToFirebase()
}
this will result in
users
-Ykasokokkpoad
name: Leroy
food: Pizza
-YJlaok9sk0sd
name: Billy
food: Tacos
which is very similar to the structure you want. There are many other ways of creating this structure. For example, you could craft the entire dictionary in code and write it all out at one time.
Pardon typo's, I wrote this on the fly.
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
// we send this
['hello', 'world']
// Firebase stores this
{0: 'hello', 1: 'world'}
Read this post for better understanding.
I have a JSON that might contain an array of string elements and I want to save it to a variable. So far I did:
import SwiftyJSON
(...)
var myUsers = [""]
if(json["arrayOfUsers"].string != nil)
{
myUsers = json["arrayOfUsers"] //this brings an error
}
The error says:
cannot subscript a value of type JSON with an index of type string
How can I pass this array safely to my variable?
You have to get the array of Strings that SwiftyJSON has prepared when it parsed your JSON data.
I will use if let rather than != nil like you do in your question, and we're going to use SwiftyJSON's .array optional getter:
if let users = json["arrayOfUsers"].array {
myUsers = users
}
If for any reason you get a type error, you can explicitly downcast the SwiftyJSON object itself instead of using the getter:
if let users = json["arrayOfUsers"] as? [String] {
myUsers = users
}
Note that your array of Strings is also not created properly. Do like this:
var myUsers = [String]()
or like hits:
var myUsers: [String] = []
Both versions are equally valid and both create an empty array of strings.
I want to create a dictionary out of an array and assign a new custom object to each of them. I'll do stuff with the objects later. How can I do this?
var cals = [1,2,3]
// I want to create out of this the following dictionary
// [1:ReminderList() object, 2:ReminderList() object, 3:ReminderList() object]
let calendarsHashedToReminders = cals.map { ($0, ReminderList()) } // Creating a tuple works!
let calendarsHashedToReminders = cals.map { $0: ReminderList() } // ERROR: "Consecutive statements on a line must be separated by ';'"
map() returns an Array so you'll either have to use reduce() or create the dictionary like this:
var calendars: [Int: ReminderList] = [:]
cals.forEach { calendars[$0] = ReminderList() }
You can also use reduce() to get a oneliner but I'm not a fan of using reduce() to create an Array or a Dictionary.
How can an array of person objects be extracted from an array of memberships that have person.personId != self.id?
For an array of memberships, each has a person object. I would like to get all the person objects directly for all other persons.
If getting the first one like this
if let memberships = self.memberships.allObjects as? [Membership],
let person = memberships.filter({$0.person.personId != userId}).first?.person {
How can every person be extracted and returned in an array using swifts collection functions?
You could try something like this:
if let memberships = self.memberships.allObjects as? [Membership] {
// Filter to remove the membership with userID,
// and then map to an array of people
let people = memberships.filter({$0.person.personId != userId}).map { $0.person }
}
Somewhere it looks like you are going to need to map an array of Memberships to an array of person objects. Hopefully if the above isn't exactly right it will point you in the right direction.
I'm storying an array of JavaScript key/value objects in a column of type Array on Parse like this:
[{"1432747073241":1.1},{"1432142558000":3.7}]
When I retrieve that column in Swift, I can see the data, but I'm unsure what data type to cast it as:
if let data = dashboardObject[graphColumn] as? [AnyObject]{
for pair in data{
println(pair)
}
}
That print yields this in the console (for the first pair):
{
1432747073241 = "1.1";
}
I can't seem to cast its contents as a Dictionary [Int:Double] and I'm guessing that means this is a string.
How do I parse this data in Swift? Thanks.
The Dictionary you should parse it to is [String: AnyObject]. It seems as if the keys of this dictionary are timestamps which you probably don't know. You could iterate through the dictionary like this:
for (key, value) in pair {
// do what you want in here with the value and/or the key
}