This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 6 years ago.
I have this code for read data from Firebase with condition, but I need multiple condition. I need one more condition for read. I don't know how to do it, I founded it isn't supported, but I need it. Can me help anyone how to do it?
ref?.queryOrdered(byChild: "project").queryEqual(toValue: "inbox").observe(.value, with: { (snapshot:FIRDataSnapshot) in
var newTasks = [Task]()
for sweet in snapshot.children {
let sweetObject = Task(snapshot: sweet as! FIRDataSnapshot)
newSweets.append(sweetObject)
}
self.tasks = newTasks
self.tableView.reloadData()
}) { (error:Error) -> Void in
print(error.localizedDescription)
}
Data in firebase:
This is not possible. You will either have to
1. filter most on the server, do the rest on the client
or
2. add a property that combines the values that you want to filter on
or
3. create a custom index programmatically
All these quotes come from this excellent answer over here at this question.
Hope this helps.
Related
This question already has answers here:
Finish all asynchronous requests before loading data?
(6 answers)
Make code with Firebase asynchronous
(1 answer)
Swift Function returning a value from asynchronous firebase call
(2 answers)
Wait for Firebase to load before returning from a function
(2 answers)
Firebase with Swift 3 counting the number of children
(3 answers)
Closed 2 years ago.
func callData() -> String? {
var name: String = ""
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("reyddatbase").child("MovieData").child("InitialMovieData").child("Ariel").child("movie_name").observeSingleEvent(of: .value, with: { (snapshot) in
name = ((snapshot.value) as! NSString) as String;
print("\(name)") // prints what I need
})
print("\(name)") // prints nothing??
return "\(name)" // returns nothing?
}
I am attempting to read data from a database based in Firebase.
I would like to simply display the text on screen which I can do from content view.
However the print statement inside the ref.child shows my title in console, while my print statement outside of it remains an empty string.
I am not sure why the different print statements do not yield the same result.
I am very new to swift and have taught myself to this point.
I presume there is a simple solution to my problem. Thank you in advance for the help!
This question already has an answer here:
way to purge all but one object types (models) in a realm
(1 answer)
Closed 4 years ago.
I know I can do it easily with the following code:
realm.delete(realm.objects(Duck.self))
realm.delete(realm.objects(Frog.self))
//...
realm.delete(realm.objects(Cat.self))
But what is the best way to delete all objects except objects of one type?
Please note that I have I lot of types, and every time when I adding new type I should modify my deleteAll method.
According to Dávid's answer:
func deleteAll(except types: Object.Type...) {
guard let realm = realm else { return }
try? realm.write {
realm.configuration.objectTypes?.filter{ type in types.contains{ $0 == type } == false}.forEach{ objectType in
realm.delete(realm.objects(objectType.self))
}
}
}
Usage:
deleteAll(except: Dog.self, Chicken.self)
I'm trying to get a distinct list of all of the values from the "flightNumber" field in my "LogLine" table. But everything I've tried has resulted in the fetch request returning the full list of flight numbers, with duplicates.
I've followed the answers from these questions:
Swift Core Data - Request with distinct results
Swift 3 - NSFetchRequest Distinct Results
But can't seem to get it to work. Here is my code:
func fetchUniqueFlightNumbers() -> [[String: Int16]]? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "LogLine")
request.resultType = NSFetchRequestResultType.dictionaryResultType
request.returnsDistinctResults = true
request.propertiesToFetch = ["flightNumber"]
do {
let results = try persistenceContainer.viewContext.fetch(request) as! [[String: Int16]]
return results
} catch {
print("Couldn't read flight numbers from DB \(error)")
return nil
}
}
The results I'm getting are:
[["flightNumber": 1], ["flightNumber": 1], ["flightNumber": 2], ["flightNumber": 2]]
I want to get the result [1,2] but I'm getting [1,1,2,2].
The attribute "flightNumber" is an Integer 16.
Is there something wrong with my code, or has something changed in Swift 4?
EDIT:
I realized that I'm only seeing this behavior in testing, when my persistent store is configured as an NSInMemoryStoreType. So it isn't as much of a problem, I'll just have to rethink the unit tests for this part of the code. I am curious why I'm seeing this difference in behavior between the two store types though.
#Chris.B I see your post is a bit old but unsolved. I just went through a similar problem but using FethchedResultControllerand I found out a lot. The problem you're having is that you're not using .propertiesToGroupBy and this is the properties you want distinct results of. It is a mandatory NSFetchRequest property and must be used in order to get distinct results. For a complete insight check my answer at my own question as is a very detailed sort of step-by-step guide. Removing duplicate objects from fetch based on object parameter UPDATED Swift
Hope it helps.
class Question: Object {
var answers = List<Answer>()
}
class Answer: Object {
dynamic var date: NSDate? = nil
dynamic var question: Question!
dynamic var correct = false
}
I have a database filled with Questions. When a user answers a question, an Answer object is created, with todays date and if the answer was correct.
With Realm, is it possible to do a query that finds the question in the database with the fewest number of correct answers?
I tried with
realm.objects(Question).filter("answers.#count == #min AND answers.correct == true")
but aggregate functions can't be combined with other aggregate functions, seems the #count and #min cant be used in the same query.
Currently, there is no easy way to query for results what you want to get.
The simple solution is adding count property for correct answers to Question object.
class Question: Object {
let answers = List<Answer>()
dynamic var correctAnswerCount = 0
}
Then you can query a question that has the fewest number of correct answers.
let fewest = realm
.objects(Question)
.sorted("correctAnswerCount", ascending: true).first
This question already has answers here:
Swift's guard keyword
(13 answers)
Closed 7 years ago.
I am confused about when to use guard and when to use if...else.
Is guard is replacement or alternative for If statement ?
Main thing want to know what are the functional benefits of guard statement for Swift language?
Any help to clear this situation will be appreciated.
Using guard might not seem much different to using if, but with guard your intention is clearer: execution should not continue if your conditions are not met. Plus it has the advantage of being shorter and more readable, so guard is a real improvement, and I'm sure it will be adopted quickly.
There is one bonus to using guard that might make it even more useful to you: if you use it to unwrap any optionals, those unwrapped values stay around for you to use in the rest of your code block. For example:
guard let unwrappedName = userName else {
return
}
print("Your username is \(unwrappedName)")
This is in comparison to a straight if statement, where the unwrapped value would be available only inside the if block, like this:
if let unwrappedName = userName {
print("Your username is \(unwrappedName)")
} else {
return
}
// this won't work – unwrappedName doesn't exist here!
print("Your username is \(unwrappedName)")
https://www.hackingwithswift.com/swift2