Fetch all relationship data - Core Data - swift

I am new to core data. I am fetching data from API and then saving them to core data.This is my dataModel.
Here is my API Structure,
{
"name" : "name here",
"content" :[
{
"homeContentItems" : [
{
"some objects" : "values",
"contentItemDetails": [
{
},
{
}
]
},
{
"some objects" : "values",
"contentItemDetails": [
{
},
{
}
]
}
]
},
{
"homeContentItems" : [
{
"some objects" : "values",
"contentItemDetails": [
{
},
{
}
]
},
{
"some objects" : "values",
"contentItemDetails": [
{
},
{
}
]
}
]
}
]
}
How can I fetch data from the Entity so I can get all data from related entity too?
I Have never worked with database before so its bit complected for me. Any help will be much appreciated.
let informedDataFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Informed360Entity")
informedDataFetch.fetchLimit = 1
informedDataFetch.predicate = NSPredicate()
let tableviewData = try! context.fetch(informedDataFetch)
let tdata : Informed360Entity = tableviewData.first as! Informed360Entity
var contentData = tdata.toContent?.allObjects as? [ContentEntity]
I tried this code and getting data from ContentEntity table. How can I get other 2 tables data too so I can use to display in tableview.

You do it the same way as you did with ContentEntity but now you use the two properties that represent the relationships, contentDetailItem and homeContentItems, which both will return a Set.
for content in contentData {
let contentDetailItems = content.contentDetailItem
let homeContents = content.homeContentItems
//...
}

Related

Use index of object in MongoDB to return result

Below is a collection in mongodb. I need to return the bus_number given a start stop and an end stop. the constraint is that that the index of the end stop has to be greater than the index of the start stop.
So, given start=226 & end=229 the returned value should be 1A.
start=229 & end=226 should return nothing.
{
"_id" : ObjectId("59be068"),
"route" : "1A",
"route_patterns" : [
{
"route_pattern_id" : "00010001",
"route_stops" : [
{
"stop_id" : "226",
},
{
"stop_id" : "228"
},
{
"stop_id" : "229"
},
{
"stop_id" : "227"
}
]
}
]}
Edit:
my structure now looks like this:
{
"route":"1A",
"route_pattern_id":"00010001",
"route_stops":[
{
"stop_id":"226",
"stop_number":0
},
{
"stop_id":"228",
"stop_number":1
},
{
"stop_id":"229",
"stop_number":2
},
{
"stop_id":"227",
"stop_number":3
}
]
}
This way I am now using the stop_number. Not a clean solution.
This is what I have done:
entity_start = db.routes.find({
"route_patterns.route_stops.stop_id": str(start_stop)
})
dumps(entity_start)
start_buses = [routes['route'] for routes in entity_start]
entity_end = db.routes.find({
"route_patterns.route_stops.stop_id": str(end_stop)
})
end_buses = [routes['route'] for routes in entity_end]
set_two = set(start_buses)
set_one = set(end_buses)
return dumps(set_one.intersection(set_two))

Getting specific value of a key from child of child data in Firebase with Swift

Hello i have a datamodel like this;
{
"users" : {
"User1" : {
"flat1" : {
"flataddress" : "adres1",
"flatname" : "n1"
},
"flat2" : {
"flataddress" : "adress2",
"flatname" : "n2"
}
},
"user2" : {
"flat3" : {
"flataddress" : "a3",
"flatname" : "n1"
},
"flat4" : {
"flataddress" : "a6",
"flatname" : "a6"
}
}
}
}
Assume that user1,user2,flat1,flat2 are some IDs formed like "3DSAZDSAPOYDZ".
First question is how can i get all the flats which flataddress = "adres1"?
Second question is, if i need to retrieve all flats, there is IDs that cannot be guessed, If i do ref.getChild("users") the userIDs are retrieved from the snapshot like;
{
"users" : {
"User1" : {
"flat1" : {
"flataddress" : "adres1",
"flatname" : "n1"
},
"flat2" : {
"flataddress" : "adress2",
"flatname" : "n2"
}
},
"user2" : {
"flat3" : {
"flataddress" : "a3",
"flatname" : "n1"
},
"flat4" : {
"flataddress" : "a6",
"flatname" : "a6"
}
}
}
}
there is user ids included already, i want something like this;
{
flat1 = {
flataddress = adres1;
flatname = n1;
}
flat2 = {
flataddress = adress2;
flatname = n2;
}
flat3 = {
flataddress = a3;
flatname = n1;
}
flat4 = {
flataddress = a6;
flatname = a6;
}
}
Thanks in advance.
Let's call your main response jsonDict.If you want to get into each dictionary, you would do:
//make an empty array to put your dictionaries in
var flatsDictArray = [[String: AnyObject]]()
//first you have to unwrap each level of the dictionary response
guard let usersDict = jsonDict["users"] as? [String: AnyObject] else {
//do something here if your json response is not what you expected
//print usersDict below if you want to see what it looks like
print(usersDict)
return
}
//below we access the keys and values in the usersDict
//obj is the key, value is the value
for (obj, value) in usersDict {
if let userFlats = value as? [String: AnyObject] {
flatsDictArray.append(userFlats)
}
}
Because of the way your JSON response is structured, flatsDictArray will have two dictionaries, each dictionary will have two keys with the JSON response listed above. So they will be sorted by flats per user.
Therefore, flatsDictArray would be:
["flat1": [flataddress: adres1,
flatname: n1],
"flat2": [flataddress: adress2,
flatname: n2]],
["flat3": [flataddress: a3,
flatname: n1],
"flat4": [flataddress: a6,
flatname = a6]]
So as you see, you can step through every level of dictionary to find a key or value the way I have, so if you need to find a value that equals something, you could do it the same way.
for(obj, value) in myLovelyDictionary {
if value == "address1" {
//do something
}
}

Trouble trying to retrieve data from Firebase

I have this piece of working code that saves data to Firebase:
let locRef = locationRef.childByAutoId()
let locItem = [
senderId : [
"location": getLocationID()
]
]
locRef.setValue(locItem)
And I want to retrieve the user's (identified by senderID) "location", so I tried this piece of code:
locationRef.child("location").child(senderId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
self.locationId = snapshot.value!["location"] as! String
}) { (error) in
print(error.localizedDescription)
}
However my app is crashing when the piece of code is run, and there are no errors. I think my mistake may be that .child("location") must be something else, but I do not know what.
Database structure (JSON):
{
"locations" : {
"-KLEdoj2eiF7EW9m0815" : {
"W6vSOHZLTwNM33JYqkKHvaIVRF13" : {
"location" : "Seattle, WA"
}
},
"-KLLfcOvYHwIufBALM0-" : {
"W6vSOHZLTwNM33JYqkKHvaIVRF13" : {
"location" : "London, United Kingdom"
}
},
Any help would be appreciated thanks!
You should be referring to your location as the following
FIRDatabase.database().reference().child("locations").child(locationId).child(senderId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
self.location = snapshot.value!["location"] as! String
}
For example:
If you have locationId = "-KLEdoj2eiF7EW9m0815" and senderId = "W6vSOHZLTwNM33JYqkKHvaIVRF13" the above call will set the self.location to "Seattle, WA"

How to achieve this format in swift?

I want to pass a parameter in my POST method. This is the valid parameter to be sent.
{
"feedback" : "Sample Feedback",
"orderId" : 1240,
"ratings" : [
{
"rateType" : 1,
"rating" : 3
},
{
"rateType" : 2,
"rating": 4
}
],
"sellerId" : 598,
"title" : "Sample title"
}
I am using this(below) to achieve that format(above) but the server returns invalid feedback. Please help me if I'm missing something or doing wrong to achieve the format above.
let parameter: [String: AnyObject] = [
"sellerId": self.sellerId,
"orderId": self.orderId,
"title": "Seller Feedback",
"feedback": "Sample Feedback",
"ratings": [[
"rateType": 1,
"rating": self.rate1
], [
"rateType": 2,
"rating": self.rate2
]]
]
Thank you!
Dictionaries are not ordered. you'll have to implement your own ordered dictionary or use a struct. here is one from http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/
struct OrderedDictionary<Tk: Hashable, Tv> {
/* ... vars and init ... */
subscript(key: Tk) -> Tv? {
get {
return self.values[key]
}
set(newValue) {
if newValue == nil {
self.values.removeValueForKey(key)
self.keys.filter {$0 != key}
return
}
let oldValue = self.values.updateValue(newValue!, forKey: key)
if oldValue == nil {
self.keys.append(key)
}
}
}
}

Search in an array of an embedded object in MongoDB

Given this structure for a school object:
{
"grade_spans" :
{
"0": {
"grade_span_key" : "K_5",
"name": "Elementary School"
},
"1": {
"grade_span_key" : "6_8",
"name": "Junior High-School"
}
}
}
How do I find a school for a given grade_span_key?
db.schools.find({ "grade_span_key": "K_5" })
returns empty.
Update: Sorry, I copied the structure incorrectly. It's actually an Embedded Object not a collection.
Update #2: There was a doctrine2 annotation I was using incorrectly: #MongoDB\EmbedMany(strategy="set"). I change the strategy to pushAll (which is the default)
If this field is just embedded into the main document #sergios answer will work just fine and it is not clear why his query wouldn't work as you don't provide an example of the document structure only of the embedded structure.
Also as #JohnnyHK says, rebuild that object as an array since dynamic keys in this case would be harder.
If you are looking to pick out matching rows from the embedded document and not the full document. This is a little harder but is possible:
db.schools.aggregate({
{$unwind: "$grade_spans"},
{$match: {"grade_spans.grade_span_key": "K_5"}},
{$group: {_id: "$_id", grade_spans: {$push: "$grade_spans"}}}
})
Something like the above should return a document of the structure:
{
_id: {},
grade_spans:[{
"grade_span_key" : "K_5",
"name" : "Elementary School"
}]
}
You should use full path to the property, in dotted notation.
> db.schools.find({"grade_spans.grade_span_key": "K_5"})
{
"_id" : ObjectId("50801cc5ab582e310adc0e41"),
"grade_spans" : [
{
"grade_span_key" : "K_5",
"name" : "Elementary School"
},
{
"grade_span_key" : "6_8",
"name" : "Junior High-School"
}
]
}
Given this structure :
{
"grade_spans" : {
"0": { "grade_span_key" : "K_5",
"name": "Elementary School" },
"1": { "grade_span_key" : "6_8",
"name": "Junior High-School" }
}
}
You can try with map/reduce function :
var mapFunction = function() {
for (var i in this.grade_spans) {
// Add the name of the school in a list
var schools = [];
schools[0] = this.grade_spans[i].name;
// Create out object : { schools : ["Elementary School"] } or { schools : ["Junior High-School"] }
var out = {};
out.schools = schools;
// Create key (K_5 or 6_8)
var key = this.grade_spans[i].grade_span_key;
emit(key, out);
}
};
var reduceFunction = function(key, values) {
var schools = [];
for (var i = 0; i < values.length; i++) {
schools.push.apply(schools, values[i].schools);
}
return {schools:schools};
}
db.schools.mapReduce(
mapFunction,
reduceFunction,
{ out: "map_reduce_grade_spans", sort: {_id:1} }
)
And then :
db.map_reduce_grade_spans.find({_id:"K_5"});