I created a function to load my drivers location from firebase and place an annotations on their current locations but when I try to simulate to test the code it crashes. I've tried on both my phone and the Xcode simulator. Below is the code that keeps crashing my app.
func loadDriverAnnotationsFromFB() {
DataService.instance.REF_DRIVERS.observeSingleEvent(of: .value, with: { (snapshot) in
if let driverSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
for drivers in driverSnapshot {
if drivers.hasChild("userIsDriver") {
if drivers.hasChild("coordinate") {
if drivers.childSnapshot(forPath: "isPickupModeEnabled").value as? Bool == true {
if let driverDict = drivers.value as? Dictionary<String, AnyObject> {
let coordinatArray = driverDict["coordinate"] as! NSArray
let driverCoordinate = CLLocationCoordinate2D(latitude: coordinatArray[0] as! CLLocationDegrees, longitude: coordinatArray[1] as! CLLocationDegrees)
let driverAnnotation = DriverAnnotation(coordinate: driverCoordinate, withKey: drivers.key)
var driverIsVisible: Bool {
return self.mapView.annotations.contains(where: { (annotation) -> Bool in
if let driverAnnotation = annotation as? DriverAnnotation {
if driverAnnotation.key == drivers.key {
driverAnnotation.update(annotationPosition: driverAnnotation, withCoordinate: driverCoordinate)
return true
}
}
return false
})
}
if !driverIsVisible {
self.mapView.addAnnotation(driverAnnotation)
}
}
}
}
}
}
}
})
}
Related
When people log in to my app, I take some data from the database like this:
func DownloadButikker() {
self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let store = Store()
store.Latitude = dictionary["Latitude"]?.doubleValue
store.Longitude = dictionary["Longitude"]?.doubleValue
store.Store = dictionary["Store"] as? String
store.Status = dictionary["Status"] as? String
stores.append(store)
}
})
self.performSegue(withIdentifier: "LogInToMain", sender: nil)
}
I perform the segue before all data has finished loading. Are there any way to get a completion to the observer or check if all data is loaded before making the segue?
The quick solution is that you need to perform your segue after finishing your async call.
func DownloadButikker() {
self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let store = Store()
store.Latitude = dictionary["Latitude"]?.doubleValue
store.Longitude = dictionary["Longitude"]?.doubleValue
store.Store = dictionary["Store"] as? String
store.Status = dictionary["Status"] as? String
stores.append(store)
}
DispatchQueue.main.async {
self.performSegue(withIdentifier: "LogInToMain", sender: nil)
}
})
}
func DownloadButikker(completion: Bool = false) {
self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let store = Store()
store.Latitude = dictionary["Latitude"]?.doubleValue
store.Longitude = dictionary["Longitude"]?.doubleValue
store.Store = dictionary["Store"] as? String
store.Status = dictionary["Status"] as? String
stores.append(store)
completion(true)
}
})
}
// In your ViewController
func myFunction() {
DownloadButikker { (hasFinished) in
if hasFinished {
self.performSegue(withIdentifier: "LogInToMain", sender: nil)
}
}
}
Newbie here.Using Google API Nearby Search. I have problem sending encapsulated data into closure, already populated table with vicinity info, but when i try to send placeID info into closure to get Details, it gives me nil.
Here i get placeID and vicinity, and afterwards populate tableView with places array. Class Place is in separate swift file, function downloadPlaceID is inside ViewController.
class Place {
var placeId: String!
var vicinity: String!
var _placeId: String {
if placeId == nil {
placeId = ""
}
return placeId
}
var _vicinity: String {
if vicinity == nil {
vicinity = ""
}
return vicinity
}
init( place: [String:Any]) {
if let ids = place["id"] as? String {
self.placeId = ids
}
if let vicinities = place["vicinity"] as? String {
self.vicinity = vicinities
}
}
}
func downloadPlaceID (completed: #escaping DownloadComplete) {
let placeURL = URL(string: nearbyURL)
Alamofire.request(placeURL!).responseJSON { (response) in
let result = response.result
if let dictionary = result.value as? [String:Any] {
if let results = dictionary["results"] as? [[String:Any]] {
if let status = dictionary["status"] as? String {
if status == "OK" {
for obj in results {
place = Place(place: obj)
// here i get all the placeID's
places.append(place)
}
}
}
}
}
completed()
}
}
Then i try to get details, into which I put placeID:
func downloadDetails( input: String, completed: DownloadComplete) {
let details = "\(detailsBaseURL)\(detailsPlaceId)\(input)\(detailsKey)\(detailsSearchAPIKey)"
print(placeID)
Alamofire.request(details).responseJSON { response in
let result = response.result
if let dictionary = result.value as? [String:Any] {
if let result = dictionary["result"] as? [String:Any] {
if let phoneNumber = result["formatted_phone_number"] as? String {
self.phone = phoneNumber
print(self.phone!)
}
if let geometry = result["geometry"] as? [String:Any] {
if let location = geometry["location"] as? [String:Any] {
if let latitude = location["lat"] as? Double {
self.lat = latitude
print(self.lat!)
}
if let longitude = location["lng"] as? Double {
self.lng = longitude
print(self.lng!)
}
}
}
if let openingHours = result["opening_hours"] as? [String:Any] {
if let openNow = openingHours["open_now"] as? Bool {
self.workHours = openNow
print(self.workHours!)
}
}
}
}
}
}
Here is code inside viewDidLoad that i'm trying to use to get details.
override func viewDidLoad() {
super.viewDidLoad()
downloadPlaceID {
detail.downloadDetails(input: place.placeId, completed: {
})
}
}
It should be "place_id" instead of "id"
class Place {
var placeId: String!
var vicinity: String!
var _placeId: String {
if placeId == nil {
placeId = ""
}
return placeId
}
var _vicinity: String {
if vicinity == nil {
vicinity = ""
}
return vicinity
}
init( place: [String:Any]) {
if let ids = place["place_id"] as? String {
self.placeId = ids
}
if let vicinities = place["vicinity"] as? String {
self.vicinity = vicinities
}
}
}
I have an iOS swift app using Firebase realtime database. If I use the app normally so far I cannot find any issue. However, I want to anticipate edge cases.
I am trying to stress test my app before I push the update, and one way I am doing it is quickly going back and forth from a VC with a tableView to the next VC which is a detail VC. If I do it several times eventually the tableview will show lots of duplicate data.
I have tested my app by having a tableview open on my simulator and going into my Firebase Console and manually changing a value and instantly on the device the string changes.
So I am confused as to why my tableview would show an incorrect amount of children if it is constantly checking what the value should be.
// MARK: Firebase Methods
func checkIfDataExits() {
DispatchQueue.main.async {
self.cardArray.removeAll()
self.ref.observe(DataEventType.value, with: { (snapshot) in
if snapshot.hasChild("cards") {
self.pullAllUsersCards()
} else {
self.tableView.reloadData()
}
})
}
}
func pullAllUsersCards() {
cardArray.removeAll()
let userRef = ref.child("users").child((user?.uid)!).child("cards")
userRef.observe(DataEventType.value, with: { (snapshot) in
for userscard in snapshot.children {
let cardID = (userscard as AnyObject).key as String
let cardRef = self.ref.child("cards").child(cardID)
cardRef.observe(DataEventType.value, with: { (cardSnapShot) in
let cardSnap = cardSnapShot as DataSnapshot
let cardDict = cardSnap.value as! [String: AnyObject]
let cardNickname = cardDict["nickname"]
let cardType = cardDict["type"]
let cardStatus = cardDict["cardStatus"]
self.cardNicknameToTransfer = cardNickname as! String
self.cardtypeToTransfer = cardType as! String
let aCard = CardClass()
aCard.cardID = cardID
aCard.nickname = cardNickname as! String
aCard.type = cardType as! String
aCard.cStatus = cardStatus as! Bool
self.cardArray.append(aCard)
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
}
})
}
I got help and changed my code drastically, so now it works
func checkIfDataExits() {
self.ref.observe(DataEventType.value, with: { (snapshot) in
if snapshot.hasChild("services") {
self.pullCardData()
} else {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
})
}
func pullCardData() {
let cardRef = self.ref.child("cards")
cardRef.observe(DataEventType.value, with: { (snapshot) in
for cards in snapshot.children {
let allCardIDs = (cards as AnyObject).key as String
if allCardIDs == self.cardID {
if let childId = self.cardID {
let thisCardLocation = cardRef.child(childId)
thisCardLocation.observe(DataEventType.value, with: { (snapshot) in
let thisCardDetails = snapshot as DataSnapshot
if let cardDict = thisCardDetails.value as? [String: AnyObject] {
self.selectedCard?.cardID = thisCardDetails.key
self.selectedCard?.nickname = cardDict["nickname"] as? String ?? ""
self.selectedCard?.type = cardDict["type"] as? String ?? ""
self.pullServicesForCard()
}
})
}
}
}
})
}
func pullServicesForCard() {
if let theId = self.cardID {
let thisCardServices = self.ref.child("cards").child(theId).child("services")
thisCardServices.observe(DataEventType.value, with: { (serviceSnap) in
if self.serviceArray.count != Int(serviceSnap.childrenCount) {
self.serviceArray.removeAll()
self.fetchAndAddAllServices(serviceSnap: serviceSnap, index: 0, completion: { (success) in
if success {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
})
}
})
}
}
func fetchAndAddAllServices(serviceSnap: DataSnapshot, index: Int, completion: #escaping (_ success: Bool) -> Void) {
if serviceSnap.hasChildren() {
if index < serviceSnap.children.allObjects.count {
let serviceChild = serviceSnap.children.allObjects[index]
let serviceID = (serviceChild as AnyObject).key as String
let thisServiceLocationInServiceNode = self.ref.child("services").child(serviceID)
thisServiceLocationInServiceNode.observeSingleEvent(of: DataEventType.value, with: { (thisSnap) in
let serv = thisSnap as DataSnapshot
if let serviceDict = serv.value as? [String: AnyObject] {
let aService = ServiceClass(serviceDict: serviceDict)
self.serviceCurrent = serviceDict["serviceStatus"] as? Bool
self.serviceName = serviceDict["serviceName"] as? String ?? ""
self.serviceURL = serviceDict["serviceURL"] as? String ?? ""
self.serviceFixedBool = serviceDict["serviceFixed"] as? Bool
self.serviceFixedAmount = serviceDict["serviceAmount"] as? String ?? ""
self.attentionInt = serviceDict["attentionInt"] as? Int
self.totalArr.append((serviceDict["serviceAmount"] as? String)!)
// self.doubleArray = self.totalArr.flatMap{ Double($0) }
// let arraySum = self.doubleArray.reduce(0, +)
// self.title = self.selectedCard?.nickname ?? ""
// if let titleName = self.selectedCard?.nickname {
// self.title = "\(titleName): \(arraySum)"
// }
aService.serviceID = serviceID
if serviceDict["serviceStatus"] as? Bool == true {
self.selectedCard?.cStatus = true
} else {
self.selectedCard?.cStatus = false
}
if !self.serviceArray.contains(where: { (service) -> Bool in
return service.serviceID == aService.serviceID
}) {
self.serviceArray.append(aService)
self.serviceArray.sort {$1.serviceAttention < $0.serviceAttention}
}
}
self.fetchAndAddAllServices(serviceSnap: serviceSnap, index: index + 1, completion: completion)
})
}
else {
completion(true)
}
}
else {
completion(false)
}
}
I followed the Firebase tutorial by Ray Wenderlich (Link) and adopted his way of initializing the object (in my case of type "Location") with the snapshot from the observe-method:
class Location:
init(snapshot: FIRDataSnapshot) {
identifier = snapshot.key
let snapshotValue = snapshot.value as! [String : AnyObject]
type = snapshotValue["type"] as! String
name = snapshotValue["name"] as! String
address = snapshotValue["address"] as! String
latitude = Double(snapshotValue["latitude"] as! String)!
longitude = Double(snapshotValue["longitude"] as! String)!
avatarPath = snapshotValue["avatarPath"] as! String
ref = snapshot.ref
}
LocationsViewController:
databaseHandle = locationsRef?.queryOrdered(byChild: "name").observe(.value, with: { (snapshot) in
var newLocations:[Location] = []
for loc in snapshot.children {
let location = Location(snapshot: loc as! FIRDataSnapshot)
newLocations.append(location)
}
self.locations = newLocations
self.tableView.reloadData()
})
This really works like a charm, but now I'm trying to load the image stored under the storage reference "avatarPath".
My attempt worked but the images take a ling time to load. Is there a better way/place to load these images?
My attempt 1:
databaseHandle = locationsRef?.queryOrdered(byChild: "name").observe(.value, with: { (snapshot) in
var newLocations:[Location] = []
for loc in snapshot.children {
let location = Location(snapshot: loc as! FIRDataSnapshot)
newLocations.append(location)
}
self.locations = newLocations
self.tableView.reloadData()
//Load images
for loc in self.locations {
let imagesStorageRef = FIRStorage.storage().reference().child(loc.avatarPath)
imagesStorageRef.data(withMaxSize: 1*1024*1024, completion: { (data, error) in
if let error = error {
print(error.localizedDescription)
} else {
loc.avatarImage = UIImage(data: data!)!
self.tableView.reloadData()
}
})
}
})
My 2nd Attempt (inside Location class):
init(snapshot: FIRDataSnapshot) {
identifier = snapshot.key
let snapshotValue = snapshot.value as! [String : AnyObject]
type = snapshotValue["type"] as! String
name = snapshotValue["name"] as! String
address = snapshotValue["address"] as! String
latitude = Double(snapshotValue["latitude"] as! String)!
longitude = Double(snapshotValue["longitude"] as! String)!
avatarPath = snapshotValue["avatarPath"] as! String
ref = snapshot.ref
super.init()
downloadImage()
}
func downloadImage() {
let imagesStorageRef = FIRStorage.storage().reference().child(self.avatarPath)
imagesStorageRef.data(withMaxSize: 1*1024*1024, completion: { (data, error) in
if let error = error {
print(error.localizedDescription)
} else {
self.avatarImage = UIImage(data: data!)!
}
})
}
Thank you in advance!
Nico
The best way you can accomplish that is to load asynchronous inside the loading of the cell function. I mean:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
DispatchQueue.main.async {
let imagesStorageRef = FIRStorage.storage().reference().child(self.locations[indexPath.row].avatarPath)
imagesStorageRef.data(withMaxSize: 1*1024*1024, completion: { (data, error) in
if let error = error {
print(error.localizedDescription)
} else {
locations[indexPath.row].avatarImage = UIImage(data: data!)!
tableView.reloadRows(at indexPaths: [indexPath], with animation: .none)
}
})
}
}
In first attempt try changing your code as:
DispatchQueue.main.async {
for loc in self.locations {
let imagesStorageRef = FIRStorage.storage().reference().child(loc.avatarPath)
imagesStorageRef.data(withMaxSize: 1*1024*1024, completion: { (data, error) in
if let error = error {
print(error.localizedDescription)
} else {
loc.avatarImage = UIImage(data: data!)!
self.tableView.reloadData()
}
})
}
}
I am currently trying to access data from a child snapshot in Swift. Here is my code that I have (which worked before the Swift 3/Firebase update):
if let achievements = snapshot1.childSnapshotForPath("Achievements").children.allObjects as? [FIRDataSnapshot] {
if achievements.count != 0 {
if let val = achievements[0].value!["somevalue"] as? Int {
self.dict["somevalue"] = val
}
}
So what I am trying to do here, is to create a variable of a child snapshot (achievements), and access child snapshot data from it. The achievements[0] will simply return the very first value. However, this doesn't seem to work. How should I approach this?
I am currently doing this inside a snapshot already (of 'observeType:.ChildAdded')
My Firebase DB looks like this:
Achievements{
randomId1 {
somevalue : somevalue
}
randomId2 {
somevalue2 : somevalue2
}
}
Updated code:
func loadData() {
ref.child("Players").observe(FIRDataEventType.childAdded) { (snapshot:FIRDataSnapshot) in
if let value = snapshot.value as? [String:AnyObject], let username = value["Username"] as? String {
}
if let value = snapshot.value as? [String:AnyObject], let ranking = value["Rank"] as? String {
}
if let childSnapshot = snapshot.childSnapshot(forPath: "Achievements").children.allObjects as? [FIRDataSnapshot] {
if childSnapshot.count != 0 {
if let achievement1 = childSnapshot[0].value!["Rookie"] as? String {
print(achievement1)
}
}
}
}
}
JSON Tree:
Players {
PlayerID {
Username
Rank
Achievements {
Rookie: yes
}
}
Try :-
if let childSnapshot = snapshot.childSnapshot(forPath: "Achievements") as? FIRDataSnapshot{
if let achievementDictionary = childSnapshot.value as? [String:AnyObject] , achievementDictionary.count > 0{
if let achieveMedal = achievementDictionary["Rookie"] as? String {
print(achieveMedal)
}
}
}