Swift check if two object have the same values - swift

I have an app that is location-based and I have two types of posts, Fixed & Dynamic I'm trying to set it up so that if a Dynamic Post and a Fix Post are at the same location it won't show the Dynamic Post and only show the Fixed Post. I just can't seem to figure out the logic behind it... Thanks for any help
Heres as far as I was able to get:
let ref = Database.database().reference().child("posts")
ref.observeSingleEvent(of: .value) { (snapshot) in
guard let dictionary = snapshot.value as? [String: Any] else { return }
dictionary.forEach { (key, value) in
guard let dict = value as? [String: Any] else { return }
guard let type = dict["type"] as? String else { return }
guard let latitudeString = dictionary["latitude"] as? String else { return }
guard let longitudeString = dictionary["longitude"] as? String else { return }
let latitude = (latitudeString as NSString).doubleValue
let longitude = (longitudeString as NSString).doubleValue
var dynamicEvents = [Post]()
Database.fetchPost(postId: key) { (post) in
if post.type == "dynamic" && post.latitude == post.latitude && post.longitude == post.longitude {
let coords = [CLLocation(latitude: latitude, longitude: longitude)]
DispatchQueue.main.async {
self.addAnnotation(post: post, title: post.category, subtitle: nil, coords: coords)
}
} else {
return
}
}
}
}

I think you just need to create an extension to compare between those object.
Or you can make these 2 objects inherit from an object which contains both : "latitude" & "longitude". In this way, you can implement the Equatable protocol to compare if they are the same.

Your logic is checking if the same variable is equal to the same variable:
post.latitude == post.latitude && post.longitude == post.longitude
I think you meant something like
post.latitude == latitude && post.longitude == longitude

Related

Multiple if let statements in Swift and Firebase

I'm trying to compare my responses with other people's responses in the firebase database. My script currently has 2 if statements saying if it's my response, record my answers and then use that to compare against other responses, but it doesn't register my second if statement.
let responsesReference = Database.database().reference().child("responses")
responsesReference.observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in
guard let json = snapshot.value as? [String: Any] else { return }
do {
var similarities = [Similarity]()
for answerElement in json {
if self.currentUser.uid == answerElement.key,
let myanswer = answerElement.value as? [String: Any] {
if self.currentUser.uid != answerElement.key, //DOES NOT REGISTER
let otheranswer = answerElement.value as? [String: Any] {
let percentage = myanswer.similarity(with: otheranswer)
similarities.append(
Similarity(name: answerElement.key, percentage: percentage, answer: otheranswer)
)
}
}
}
self.similarities = similarities.sorted(by: { (a, b) -> Bool in
return a.percentage > b.percentage
})
self.tableView.reloadData()
}
Here's your code properly formatted (I copy and pasted it with no changes other than formatting it)
do {
var similarities = [Similarity]()
for answerElement in json {
if self.currentUser.uid == answerElement.key, let myanswer = answerElement.value as? [String: Any] {
if self.currentUser.uid != answerElement.key, let otheranswer = answerElement.value as? [String: Any] {
let percentage = myanswer.similarity(with: otheranswer)
similarities.append( Similarity(name: answerElement.key, percentage: percentage, answer: otheranswer) )
}
}
Take a look here
if self.currentUser.uid == answerElement.key
and note the next if is nested inside that one
if self.currentUser.uid == answerElement.key
if self.currentUser.uid != answerElement.key
If those two vars are equal in the outside if, they will be equal with the inside if as well so the second check will always fail.
The generic solution is to use and else with your if
if self.currentUser.uid == answerElement.key {
let myanswer = answerElement.value as? [String: Any] <- OPTIONAL!
//do something because they are equal
} else {
let otheranswer = answerElement.value as? [String: Any] <- OPTIONAL!
// do something else because they are NOT equal
}
also note that you've got some optionals in that code and if those go to nil your app will either crash or silently fail with no indication as to why.
The logic isn't exactly clear in this code
let percentage = myanswer.similarity(with: otheranswer)
as each time through the loop
for answerElement in json {
}
there will only be one answer in an answerElement. e.g. there won't be a myAnswer and otherAnswer, there will only be theAnswer. Perhaps there should be a comparison to the prior answer from the loop; I'll expand on that
Here's an example based on reading in all users, getting the answer for this user, removing the user from the results and then comparing that to other users answers. Assume users uid's are used at the key to each user node (which also contains an answer they provides) and we know the auth'd users uid.
let thisUsersUid = "uid_1"
let usersRef = self.ref.child("users") //self.ref points to MY firebase
usersRef.observeSingleEvent(of: .value, with: { snapshot in
var allUsersSnap = snapshot.children.allObjects as! [DataSnapshot]
guard let index = allUsersSnap.firstIndex { $0.key == thisUsersUid } else {
print("no user: \(thisUsersUid) found")
return
}
let thisUserSnap = allUsersSnap[index] //keep this so it can be compared later
allUsersSnap.remove(at: index)
let thisUsersAnswer = thisUserSnap.childSnapshot("answer").value as? String ?? "No Answer"
for otherUserSnap in allUsersSnap {
let otherUsersAnswer = otherUserSnap.childSnapshot("answer").value as? String ?? "No Answer"
if orherUsersAnswer == thisUsersAnswer {
//do something because the answers match
}
}
})

Swift Firestore prevent checking if Dictionary key exists

I have this chunk of code which returns the results from a Firestore query. Because I want to make sure that the values exists I'm checking every single one of them like if let driverLat = packageDetails["driverLat"] as? Double.. etc and also casting them. It is getting really annoying and I was wondering if there is a better solution to this?
db.collection("packages").document(documentID).getDocument() { (document, error) in
if let document = document, document.exists {
if let packageDetails = document.data() as [String: AnyObject]? {
if let driverLat = packageDetails["driverLat"] as? Double, let driverLon = packageDetails["driverLon"] as? Double {
if let destinationLat = packageDetails["destinationLat"] as? Double, let destinationLon = packageDetails["destinationLon"] as? Double {
// more code
}
}
}
}
}
I would say that you should use multiple guard-let statements. This prevents the pyramid shaped code which decreases the readability.
It would look like so:
typealias Json = [String: AnyObject]
db.collection("packages").document(documentID).getDocument() { (document, error) in
guard let document = document, document.exists else { return }
guard let packageDetails = document.data() as Json? else { return }
guard let driverLat = packageDetails["driverLat"] as? Double else { return }
guard let driverLon = packageDetails["driverLon"] as? Double else { return }
guard let destinationLat = packageDetails["destinationLat"] as? Double else { return }
guard let destinationLon = packageDetails["destinationLon"] as? Double else { return }
// more code
}

Firebase don't send me my value into my variable

I've got a code which normally should return to me a value from Firebase.
My Firebase struct is :
Experience{
UserId{
LDG_DAY: "4"
LDG_NIGHT: "0"
APCH_IFR: "0"
}
}
My code is :
func getUserExp(){
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
let Date = self.flightDate.text
ref.child("Experience")/*.child(userID!)*/.observeSingleEvent(of: .value) {(snapshot) in
if snapshot.hasChild(userID!){
let value = snapshot.value as? NSDictionary
let ldg_day = value?["LDG_DAY"] as? String ?? "123"
let ldg_night = value?["LDG_NIGHT"] as? String ?? "0"
let apch_ifr = value?["APCH_IFR"] as? String ?? "0"
self.intLdgDay = Int(ldg_day)!
self.intLdgNight = Int(ldg_night)!
self.intApchIfr = Int(apch_ifr)!
print("string = \(ldg_day) int = \(self.intLdgDay)")
}
}
}
Now the code didn't work as I would like... In fact my code return the basic as? String ?? "123" value but the snapshot.value get the good value from firebase ...
What's wrong ? I use this code for many other part of my app and no problems about it ?
Thanks for your help
I believe you want to ensure the node exists before trying to read the child data.
NOTE:
I see the path to read has the uid commented out so it's unclear if you intended to read a single user (leaving in the uid) or if you actually wanted to load every user at one time (thousands). This answer assumes you are intending to read that specific user node only. See #Callam answer if you intended to read ALL of the users nodes at one time.
The code you have now is using snapshot.hasChild which looks within the node to see if the child, the users uid exists, and it doesn't so the code will always fail.
if snapshot.hasChild(userID!)
I think what you want to do is use snapshot.exists to ensure it's a valid node before reading. Here's the code:
let experienceRef = self.ref.child("Experience")
let usersExpRef = experienceRef.child(uid)
usersExpRef.observeSingleEvent(of: .value) { snapshot in
if snapshot.exists() {
let value = snapshot.value as! [String: Any]
let ldg_day = value["LDG_DAY"] as? String ?? "123"
print("string = \(ldg_day)")
} else {
print("the \(uid) node does not exist")
}
}
I would also suggest safely unwrapping options before attempting to work with them as they could be nil, and that would crash your code.
guard let thisUser = Auth.auth().currentUser else { return }
let uid = thisUser.uid
Note I also replaced the old objc NSDictionary with it's Swifty counterpart [String: Any]
Assuming your struct is from the root, and Experience contains more than one user ID, your code is currently observing the value for all user IDs since the /*.child(userID!)*/ is commented out.
Therefore you are requesting every user's experience and checking on the client if the current user exists as a child – this will succeed if the current user's ID is present at Experience/$uid.
ref.child("Experience")/*.child(userID!)*/.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.hasChild(userID!) {
let value = snapshot.value as? NSDictionary
Now we have a snapshot with all Experiences and we've confirmed that it has a child for the current user's ID – we would need to get that child and cast the value of that to a dictionary.
let value = snapshot.childSnapshot(forPath: userID).value as? NSDictionary
This fixes the issue but obviously, we don't want to download every experience on a single user's device, and they maybe shouldn't even have the permission to request that reference location either.
So if you uncomment .child(userID!), the snapshot will be of just one Experience, so snapshot.hasChild(userID!) will fail. Instead, you can use snapshot.exists() and/or a conditional cast to determine if the snapshot for the userID is existent and/or thereby castable.
func getUserExp() {
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
let Date = self.flightDate.text
ref.child("Experience").child(userID!).observeSingleEvent(of: .value) { snapshot in
if snapshot.exists() {
let value = snapshot.value as? [String:String]
let ldg_day = value?["LDG_DAY"] ?? "123"
let ldg_night = value?["LDG_NIGHT"] ?? "0"
let apch_ifr = value?["APCH_IFR"] ?? "0"
self?.intLdgDay = Int(ldg_day)!
self?.intLdgNight = Int(ldg_night)!
self?.intApchIfr = Int(apch_ifr)!
print("string = \(ldg_day) int = \(self.intLdgDay)")
} else {
print("experience for \(snapshot.key) doesn't exist")
}
}
}
You can clean this up a bit with a struct and extension.
// Experience.swift
struct Experience {
var ldg_day: String
var ldg_night: String
var apch_ifr: String
}
extension Experience {
static var currentUserRef: DatabaseReference? {
return Auth.auth().currentUser.flatMap {
return Database.database().reference(withPath: "Experience/\($0.uid)")
}
}
init?(snapshot: DataSnapshot) {
guard snapshot.exists() else { return nil }
let value = snapshot.value as? [String:String]
self.ldg_day = value?["LDG_DAY"] ?? "123"
self.ldg_night = value?["LDG_NIGHT"] ?? "0"
self.apch_ifr = value?["APCH_IFR"] ?? "0"
}
}
Et voilà,
func getUserExp() {
Experience.currentUserRef?.observeSingleEvent(of: .value, with: { [weak self] in
if let experience = Experience(snapshot: $0) {
self?.intLdgDay = Int(experience.ldg_day)!
self?.intLdgNight = Int(experience.ldg_night)!
self?.intApchIfr = Int(experience.apch_ifr)!
print("string = \(experience.ldg_day) int = \(self.intLdgDay)")
} else {
print("experience for \($0.key) doesn't exist")
}
})
}

facing Issue in parsing in swift3

I am trying to parse the emergency data in into emergency struct but it never statifies the condition and get into else case.Here is my code and structure.Some thing i have written woring in first line.
if let emergencyDict = snapshotValue["emergency"] as? [String:[String:Any]]{
for (emerId, emerData) in emergencyDict {
let emer = Emergency.init(emergency: emerData as NSDictionary)
emergency.append(emer)
}
}
else{
let emer = Emergency.init(emerg: "" as AnyObject)
emergency.append(emer)
}
struct Emergency{
var emer_id: String
var emer_name: String
var emer_phoneNo: String
init(emergency: NSDictionary) {
if emergency.object(forKey: "id") != nil {
emer_id = emergency.object(forKey: "id") as! String
}
else{
emer_id = ""
}
}
}
The problem you are having emergency as Array with type [Any] and if you remove the first object then you get Array of type [[String:Any]]. So try like this way.
if let array = snapshotValue["emergency"] as? [Any],
let emergencyArrar = Array(array.dropFirst()) as? [[String:Any]] {
print(emergencyArray)
for emergency in emergencyArray {
print(emergency)
}
}
You have written wrong in this line:
if let emergencyDict = snapshotValue["emergency"] as? [String:[String:Any]]{
It should be:
if let emergencyDict = snapshotValue["emergency"] as? [[String:Any]]{
This question should belong to query from firebase database.
// you have to get the children in emergency,
// then get the value(dictionary) of each child
ref.child("emergency").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let keys = value?.allKeys // [1, 2, 3 ....]
for key in keys {
ref.child("emergency").child(key)..observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
// Here is your dictionary
}
}
}) { (error) in
print(error.localizedDescription)
}

possible to cast this Alamofire result to an array of dictionaries

I am not an iOS dev and have to make a few changes to a Swift / AlamoFire project (not mine) and am a bit lost.
I have the following JSON:
{"metro_locations":
[
{
"name":"Ruby Red"
},
{
"name":"Blue Ocean"
}
]
}
class (I know that there are issues here):
class Location{
var name=""
init(obj:tmp){
self.name=tmp["name"]
}
}
and need to make an AlamoFire call
Alamofire.request(.GET, "https://www.domain.com/arc/v1/api/metro_areas/1", parameters: nil)
.responseJSON { response in
if let dataFromNetworking = response.result.value {
let metroLocations = dataFromNetworking["metro_locations"]
var locations: [Location]=[]
for tmp in metroLocations as! [Dictionary] { // <- not working, Generic Paramter 'Key' could not be inferred
let location=Location.init(obj: tmp)
locations.append(location)
}
}
}
I have included the error msg, the "not working" but feel that there are issues in other parts too (like expecting a dictionary in the initialization). What does the 'Key' could not be inferred mean and are there other changes I need to make?
edit #1
I have updated my Location to this to reflect your suggestion:
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] else { return nil }
guard let name = dictionary["name"] else { return nil }
guard let latitude = dictionary["latitude"] else { return nil }
guard let longitude = dictionary["longitude"] else { return nil }
self.name = name as! String
self.id = id as! Int
self.latitude = latitude as! Double
self.longitude = longitude as! Double
}
but I get the error:
Could not cast value of type 'NSNull' (0x10f387600) to 'NSNumber' (0x10f77f2a0).
like this:
I would think that the guard statement would prevent this. What am I missing?
You can cast metroLocations as an array of dictionaries, namely:
Array<Dictionary<String, String>>
Or, more concisely:
[[String: String]]
Thus:
if let dataFromNetworking = response.result.value {
guard let metroLocations = dataFromNetworking["metro_locations"] as? [[String: String]] else {
print("this was not an array of dictionaries where the values were all strings")
return
}
var locations = [Location]()
for dictionary in metroLocations {
if let location = Location(dictionary: dictionary) {
locations.append(location)
}
}
}
Where
class Location {
let name: String
init?(dictionary: [String: String]) {
guard let name = dictionary["name"] else { return nil }
self.name = name
}
}
Clearly, I used [[String: String]] to represent an array of dictionaries where the values were all strings, as in your example. If the values included objects other than strings (numbers, booleans, etc.), then you might use [[String: AnyObject]].
In your revision, you show us a more complete Location implementation. You should avoid as! forced casting, and instead us as? in the guard statements:
class Location {
let id: Int
let name: String
let latitude: Double
let longitude: Double
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? Int,
let name = dictionary["name"] as? String,
let latitude = dictionary["latitude"] as? Double,
let longitude = dictionary["longitude"] as? Double else {
return nil
}
self.name = name
self.id = id
self.latitude = latitude
self.longitude = longitude
}
}