How to convert FIRDataSnapshot in array of dictionaries? Swift 3 - ios

I have created 'struct FireBaseData' which enables me to retrieve data from Firebase. I would like to convert the data into an array of dictionaries and then output the content to Desktop in a .txt file.
How can I convert self.bookingInfo to an array of dictionaries?
func startObservingDB() {
dbRef.child(FullData.uid!).observe(.value, with: { (snapshot: FIRDataSnapshot) in
// an instance of FireBaseData holding all bookings under currentUid
var newBookingInfo = [FireBaseData]()
//iterate over all children under /FullData.uid! path
for customer in snapshot.children {
//the customer node starting with cus...
let customerObject = customer as! FIRDataSnapshot
//customer key
self.customerKey = customerObject.key
print("this is the Stripe customer that can be charged \(customerObject.key)")
//now iterate over each booking which is located under customerObject in Firebase
for booking in customerObject.children {
// after each iteration through snapshot.children, create an instance of FireBaseData with 'booking' for the current iteration & assign it to bookingItem
var bookingItem = FireBaseData(snapshot: booking as! FIRDataSnapshot)
//assign key of the parent to each booking
bookingItem.Key = self.customerKey
// append the bookingItem after each iteration to newBookingInfo array
newBookingInfo.append(bookingItem)
} // end of for booking in myCustomer
} // end of for customer in snapshot.children
//assign newBookingInfo to global variable
self.bookingInfo = newBookingInfo
// sort the array in place so that the most recent date will appear first
self.bookingInfo.sort(by: {(DateAndTimeObject_1,DateAndTimeObject_2) -> Bool in
DateAndTimeObject_1.TimeStampDateAndTime > DateAndTimeObject_2.TimeStampDateAndTime
})
let arrayOfDictionary = self.bookingInfo.flatMap { $0.toAnyObject() as? [String:Any] }
let stringSeparated = arrayOfDictionary.joined(separator: "-")
print("stringSeparated \(stringSeparated)")
self.tableView.reloadData()
}, withCancel: { (Error:Any) in
print("Error firebase \(Error)")
})
} // end of startObservingDB()
//Model to retrive data
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
struct FireBaseData {
// Create our Firebase Data model
// get arbitrary data
var FirebaseUserID:String!
var PaymentID:String!
var BookingAmount:String!
var BookingNumber:String!
var Key:String!
var PostCode:String!
var SelectedBathRow:Int!
var SelectedBedRow:Int!
var DateAndTime:String!
var TimeStampDateAndTime:Int!
var TimeStampBookingSavedInDB:Int!
var BookingStatusClient:Bool!
var BookingStatusAdmin:Bool!
var BookingCompleted:Bool!
//used in RootController and RootController1 to determine if the booking has already been cancelled or not
var CostToCancelClient:String!
var CostToCancelAdmin:String!
var CostToRescheduleAdmin:String!
var CostToRescheduleClient:String!
var DoormanOption:String!
var EntryInstructions:String!
var NoteInstructions:String!
var FrequencyName:String!
var FrequecyAmount:Int!
var insideCabinets:Bool!
var insideFridge:Bool!
var insideOven:Bool!
var laundryWash:Bool!
var interiorWindows:Bool!
var SuppliesName:String!
var SuppliesAmount:Int!
var FullName:String!
var FlatNumber:String!
var StreetAddress:String!
var PhoneNumber:String!
var EmailAddress:String!
let Ref:FIRDatabaseReference?
init(BookingAmount:String,
BookingNumber:String,
PostCode:String,
SelectedBathRow:Int,
SelectedBedRow:Int,
DateAndTime:String,
TimeStampDateAndTime:Int,
BookingStatusClient:Bool,
BookingStatusAdmin:Bool,
BookingCompleted:Bool,
FrequencyName:String,
FrequecyAmount:Int,
insideCabinets:Bool,
insideFridge:Bool,
insideOven:Bool,
laundryWash:Bool,
interiorWindows:Bool,
FullName:String,
SuppliesName:String,
SuppliesAmount:Int,
FlatNumber:String,
StreetAddress:String,
PhoneNumber:String,
EmailAddress:String,
Key:String = "") {
self.BookingAmount = BookingAmount
self.BookingNumber = BookingNumber
self.Key = Key
self.PostCode = PostCode
self.SelectedBathRow = SelectedBathRow
self.SelectedBedRow = SelectedBedRow
self.DateAndTime = DateAndTime
self.TimeStampDateAndTime = TimeStampDateAndTime
self.BookingStatusClient = BookingStatusClient
self.BookingStatusAdmin = BookingStatusAdmin
self.BookingCompleted = BookingCompleted
self.FrequencyName = FrequencyName
self.FrequecyAmount = FrequecyAmount
self.insideCabinets = insideCabinets
self.insideFridge = insideFridge
self.insideOven = insideOven
self.laundryWash = laundryWash
self.interiorWindows = interiorWindows
self.FullName = FullName
self.SuppliesName = SuppliesName
self.SuppliesAmount = SuppliesAmount
self.FlatNumber = FlatNumber
self.StreetAddress = StreetAddress
self.PhoneNumber = PhoneNumber
self.EmailAddress = EmailAddress
self.Ref = nil
}
// Content
// receive data from our firebase database
init(snapshot:FIRDataSnapshot){
if let firebaseUserID = (snapshot.value! as? NSDictionary)?["FirebaseUserID"] as? String {
FirebaseUserID = firebaseUserID
}
if let paymentID = (snapshot.value! as? NSDictionary)?["PaymentID"] as? String {
PaymentID = paymentID
}
if let BookingAmountContent = (snapshot.value! as? NSDictionary)?["BookingAmount"] as? String {
BookingAmount = BookingAmountContent
}
if let BookingNumberContent = (snapshot.value! as? NSDictionary)?["BookingNumber"] as? String {
BookingNumber = BookingNumberContent
}
Key = snapshot.key
Ref = snapshot.ref
if let PostCodeContent = (snapshot.value! as? NSDictionary)?["PostCode"] as? String {
PostCode = PostCodeContent
}
if let SelectedBathRowContent = (snapshot.value! as? NSDictionary)?["SelectedBathRow"] as? String {
SelectedBathRow = Int(SelectedBathRowContent)
}
if let SelectedBedRowContent = (snapshot.value! as? NSDictionary)?["SelectedBedRow"] as? String {
SelectedBedRow = Int(SelectedBedRowContent)
}
if let DateAndTimeContent = (snapshot.value! as? NSDictionary)?["DateAndTime"] as? String {
DateAndTime = DateAndTimeContent
}
if let TimeStampDateAndTimeContent = (snapshot.value! as? NSDictionary)?["TimeStampDateAndTime"] as? String {
TimeStampDateAndTime = Int(TimeStampDateAndTimeContent)
}
if let TimeStampBookingSavedInDBContent = (snapshot.value! as? NSDictionary)?["TimeStampBookingSavedInDB"] as? String {
TimeStampBookingSavedInDB = Int(TimeStampBookingSavedInDBContent)
}
if let BookingStatusClientContent = (snapshot.value! as? NSDictionary)?["BookingStatusClient"] as? String{
BookingStatusClient = Bool(BookingStatusClientContent)
}
if let BookingStatusAdminContent = (snapshot.value! as? NSDictionary)?["BookingStatusAdmin"] as? String {
BookingStatusAdmin = Bool(BookingStatusAdminContent)
}
if let BookingCompletedContent = (snapshot.value! as? NSDictionary)?["BookingCompleted"] as? String {
BookingCompleted = Bool(BookingCompletedContent)
}
if let costToCancelCient = (snapshot.value! as? NSDictionary)?["CostToCancelClient"] as? String {
CostToCancelClient = costToCancelCient
}
if let costToCancelAdmin = (snapshot.value! as? NSDictionary)?["CostToCancelAdmin"] as? String {
CostToCancelAdmin = costToCancelAdmin
}
if let costToRescheduleAdmin = (snapshot.value! as? NSDictionary)?["CostToRescheduleAdmin"] as? String {
CostToRescheduleAdmin = costToRescheduleAdmin
}
if let costToRescheduleClient = (snapshot.value! as? NSDictionary)?["CostToRescheduleClient"] as? String {
CostToRescheduleClient = costToRescheduleClient
}
if let doormanOption = (snapshot.value! as? NSDictionary)?["DoormanOption"] as? String {
DoormanOption = doormanOption
}
if let entryInstructions = (snapshot.value! as? NSDictionary)?["EntryInstructions"] as? String {
EntryInstructions = entryInstructions
}
if let noteInstructions = (snapshot.value! as? NSDictionary)?["NoteInstructions"] as? String {
NoteInstructions = noteInstructions
}
if let FrequencyNameContent = (snapshot.value! as? NSDictionary)?["FrequencyName"] as? String {
FrequencyName = FrequencyNameContent
}
if let FrequecyAmountContent = (snapshot.value! as? NSDictionary)?["FrequecyAmount"] as? String {
FrequecyAmount = Int(FrequecyAmountContent)
}
if let insideCabinetsContent = (snapshot.value! as? NSDictionary)?["InsideCabinets"] as? String {
insideCabinets = Bool(insideCabinetsContent)
}
if let insideFridgeContent = (snapshot.value! as? NSDictionary)?["InsideFridge"] as? String {
insideFridge = Bool(insideFridgeContent)
}
if let insideOvenContent = (snapshot.value! as? NSDictionary)?["InsideOven"] as? String {
insideOven = Bool(insideOvenContent)
}
if let laundryWashContent = (snapshot.value! as? NSDictionary)?["LaundryWash"] as? String {
laundryWash = Bool(laundryWashContent)
}
if let interiorWindowsContent = (snapshot.value! as? NSDictionary)?["InteriorWindows"] as? String {
interiorWindows = Bool(interiorWindowsContent)
}
if let FullNameContent = (snapshot.value! as? NSDictionary)?["FullName"] as? String {
FullName = FullNameContent
}
if let SuppliesNameContent = (snapshot.value! as? NSDictionary)?["SuppliesName"] as? String {
SuppliesName = SuppliesNameContent
}
if let SuppliesAmountContent = (snapshot.value! as? NSDictionary)?["SuppliesAmount"] as? String {
SuppliesAmount = Int(SuppliesAmountContent)
}
if let FlatNumberContent = (snapshot.value! as? NSDictionary)?["FlatNumber"] as? String {
FlatNumber = FlatNumberContent
}
if let StreetAddressContent = (snapshot.value! as? NSDictionary)?["StreetAddress"] as? String {
StreetAddress = StreetAddressContent
}
if let PhoneNumberContent = (snapshot.value! as? NSDictionary)?["PhoneNumber"] as? String {
PhoneNumber = PhoneNumberContent
}
if let EmailAddressContent = (snapshot.value! as? NSDictionary)?["EmailAddress"] as? String {
EmailAddress = EmailAddressContent
}
}
func toAnyObject() -> AnyObject {
var someDict = [String : Any]()
someDict["FirebaseUserID"] = self.FirebaseUserID as AnyObject?
someDict["PaymentID"] = self.PaymentID as AnyObject?
someDict["BookingAmount"] = self.BookingAmount as AnyObject?
someDict["BookingNumber"] = self.BookingNumber as AnyObject?
someDict["PostCode"] = self.PostCode as AnyObject?
someDict["SelectedBathRow"] = self.SelectedBathRow as AnyObject?
someDict["SelectedBedRow"] = self.SelectedBedRow as AnyObject?
someDict["DateAndTime"] = self.DateAndTime as AnyObject?
someDict["TimeStampDateAndTime"] = self.TimeStampDateAndTime as AnyObject?
someDict["TimeStampBookingSavedInDB"] = self.TimeStampBookingSavedInDB as AnyObject?
someDict["BookingStatusClient"] = self.BookingStatusClient as AnyObject?
someDict["BookingStatusAdmin"] = self.BookingStatusAdmin as AnyObject?
someDict["BookingCompleted"] = self.BookingCompleted as AnyObject?
someDict["CostToCancelClient"] = self.CostToCancelClient as AnyObject?
someDict["CostToCancelAdmin"] = self.CostToCancelAdmin as AnyObject?
someDict["CostToRescheduleAdmin"] = self.CostToRescheduleAdmin as AnyObject?
someDict["CostToRescheduleClient"] = self.CostToRescheduleClient as AnyObject?
someDict["DoormanOption"] = self.DoormanOption as AnyObject?
someDict["EntryInstructions"] = self.EntryInstructions as AnyObject?
someDict["NoteInstructions"] = self.NoteInstructions as AnyObject?
someDict["FrequencyName"] = self.FrequencyName as AnyObject?
someDict["FrequecyAmount"] = self.FrequecyAmount as AnyObject?
someDict["insideCabinets"] = self.insideCabinets ? "true" : "false"
someDict["insideFridge"] = self.insideFridge ? "true" : "false"
someDict["insideOven"] = self.insideOven ? "true" : "false"
someDict["laundryWash"] = self.laundryWash ? "true" : "false"
someDict["interiorWindows"] = self.interiorWindows ? "true" : false
someDict["FullName"] = self.FullName as AnyObject?
someDict["SuppliesName"] = self.SuppliesName as AnyObject?
someDict["SuppliesAmount"] = self.SuppliesAmount as AnyObject?
someDict["FlatNumber"] = self.FlatNumber as AnyObject?
someDict["StreetAddress"] = self.StreetAddress as AnyObject?
someDict["PhoneNumber"] = self.PhoneNumber as AnyObject?
someDict["EmailAddress"] = self.EmailAddress as AnyObject?
return someDict as AnyObject
}
}
Desired Output as per Nirav request
EmailAddress": johnmm#gmail.com,
"PhoneNumber": 07476953923,
"PaymentID": ch_1ARd6yLCZ34Ur7XG4wAqaH9H,
"BookingAmount": 27
EmailAddress": Chris#gmail.com,
"PhoneNumber": 07476953923,
"PaymentID": ch_1ARd6yLCZ34Ur7XG4wAqaH9H,
"BookingAmount": 27
EmailAddress": Mike#gmail.com,
"PhoneNumber": 07476953923,
"PaymentID": ch_1ARd6yLCZ34Ur7XG4wAqaH9H,
"BookingAmount": 27

What you need is to just use toAnyObject() method to get the dictionary object from your FireBaseData like this.
let arrayOfDictionary = self.bookingInfo.flatMap { $0.toAnyObject() as? [String:Any] }
You will get your desired result in arrayOfDictionary it is type of [[String:Any]]

Related

How to get the attribute from model class and pass to collection view in swift 3

Here I am having collection view in which data will be passing from model class here I need to get special_price key value pair from CustomAttribute and need to pass for collection view in which only some products will have special price and some products won't have special price how to pass the data to collection view I am unable to implement it can anyone help me how to pass data new to swift 3 if anything wrong in declaring or writing model class please correct me ?
var listClassModel : ModelClass?
var items = [List]()
func listCategoryDownloadJsonWithURL(listUrl: String) {
print(listUrl)
let url = URL(string: listUrl)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:AnyObject] {
let objArr = jsonObj["items"] as? [[String:Any]]
let objAdd = objArr!.map{List(dict: $0)}
self.items.append(contentsOf: objAdd)
self.listClassModel = ModelClass(dict: jsonObj as [String : AnyObject])
DispatchQueue.main.async {
guard let obj = self.listClassModel else { return }
let itemsCount = obj.items.count
print(itemsCount)
for i in 0..<itemsCount {
let customAttribute = obj.items[i].customAttribute
print(customAttribute.count)
for j in 0..<customAttribute.count {
if customAttribute[j].attributeCode == "image" {
let baseUrl = "http://192.168.1.11/magento2/pub/media/catalog/product"
self.listCategoryImageArray.append(baseUrl + customAttribute[j].value)
}
if customAttribute[j].attributeCode == "special_price" {
self.specialPrice.append(customAttribute[j].value)
}
}
}
print(self.specialPrice)
self.activityIndicator.stopAnimating()
self.activityIndicator.hidesWhenStopped = true
self.collectionView.reloadData()
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.isHidden = false
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}
Here is my model class
struct ModelClass {
var items : [List]
var totalCount : Int
var searchCriteria : SearchCriteria
init(dict:[String:AnyObject]) {
totalCount = dict["total_count"] as! Int
let searchDict = dict["search_criteria"] as? [String:AnyObject]
searchCriteria = SearchCriteria(dict: searchDict!)
let arr = dict["items"] as? [[String:AnyObject]]
var listArr = [List]()
for obj in arr! {
listArr.append(List(dict: obj))
}
items = listArr
}
}
struct List {
let name : String
let sku : Any
let id : Int
let attributeSetId : Int
let price : Int
let status : Int
let visibility : Int
let typeId: String
let createdAt : Any
let updatedAt : Any
var customAttribute = [ListAttribute]()
init(dict : [String:Any]) {
if let customAttribute = dict["custom_attributes"] as? [[String: AnyObject]] {
var result = [ListAttribute]()
for obj in customAttribute {
result.append(ListAttribute(json: obj)!)
}
self.customAttribute = result
} else {
self.customAttribute = [ListAttribute]()
}
self.name = (dict["name"] as? String)!
self.sku = dict["sku"]!
self.id = (dict["id"] as? Int)!
self.attributeSetId = (dict["attribute_set_id"] as? Int)!
self.price = (dict["price"] as? Int)!
self.status = (dict["status"] as? Int)!
self.visibility = (dict["visibility"] as? Int)!
self.typeId = (dict["type_id"] as? String)!
self.createdAt = dict["created_at"]!
self.updatedAt = dict["updated_at"]!
}
}
struct ListAttribute {
let attributeCode : String
let value : String
init?(json : [String:AnyObject]) {
self.attributeCode = (json["attribute_code"])! as! String
self.value = (json["value"])! as! String
}
}
Here is my image how my Json looks

How to write model class for json data with dictionary?

In this class already i had written model class but here some of the data has been added newly but i am trying to create for the model class for remaining dictionaries but unable to implement it can anyone help me how to implement it ?
In this already i had implemented model class for items array and here i need to create a model class for search criteria dictionary and inside arrays
func listCategoryDownloadJsonWithURL() {
let url = URL(string: listPageUrl)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
let objArr = jsonObj["items"] as? [[String:Any]]
self.list = objArr!.map{List(dict: $0)}
DispatchQueue.main.async {
let itemsCount = self.list.count
for i in 0..<itemsCount {
let customAttribute = self.list[i].customAttribute
for j in 0..<customAttribute.count {
if customAttribute[j].attributeCode == "image" {
let baseUrl = "http://192.168.1.11/magento2/pub/media/catalog/product"
self.listCategoryImageArray.append(baseUrl + customAttribute[j].value)
}
}
}
self.activityIndicator.stopAnimating()
self.activityIndicator.hidesWhenStopped = true
self.collectionView.reloadData()
self.collectionView.isHidden = false
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}
struct List {
let name : String
let sku : Any
let id : Int
let attributeSetId : Int
let price : Int
let status : Int
let visibility : Int
let typeId: String
let createdAt : Any
let updatedAt : Any
var customAttribute = [ListAttribute]()
init(dict : [String:Any]) {
if let customAttribute = dict["custom_attributes"] as? [[String: AnyObject]] {
var result = [ListAttribute]()
for obj in customAttribute {
result.append(ListAttribute(json: obj as! [String : String])!)
}
self.customAttribute = result
} else {
self.customAttribute = [ListAttribute]()
}
self.name = (dict["name"] as? String)!
self.sku = dict["sku"]!
self.id = (dict["id"] as? Int)!
self.attributeSetId = (dict["attribute_set_id"] as? Int)!
self.price = (dict["price"] as? Int)!
self.status = (dict["status"] as? Int)!
self.visibility = (dict["visibility"] as? Int)!
self.typeId = (dict["type_id"] as? String)!
self.createdAt = dict["created_at"]!
self.updatedAt = dict["updated_at"]!
}
}
struct ListAttribute {
let attributeCode : String
let value : String
init?(json : [String:String]) {
self.attributeCode = (json["attribute_code"])!
self.value = (json["value"])!
}
}

I am unable to get the child names from given url in swift 3?

In the api am getting global array but in this I am unable to get the children names as separate array only the last loaded array name has been getting in the array how to get the all children names in the array please help me how to get all the names in it and here is my code already tried
var detailsArray = NSArray()
var globalArray = NSMutableArray()
let url = "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2"
func downloadJsonWithURL() {
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
self.detailsArray = (jsonObj?.value(forKey: "data") as? [[String: AnyObject]])! as NSArray
print(self.detailsArray)
for item in self.detailsArray
{
let majorDic = NSMutableDictionary()
let detailDict = item as! NSDictionary
print(detailDict["name"]!)
majorDic .setValue(detailDict["name"]!, forKey: "name")
print(detailDict["children"]!)
if !(detailDict["children"]! is NSNull)
{
let children = detailDict["children"]! as! NSArray
let childrenstring = NSMutableString()
if children.count > 0 {
for item in children{
let chilDic = item as! NSDictionary
print(chilDic["name"]!)
print(chilDic["products"]!)
majorDic.setValue(chilDic["name"]!, forKey: "Childernname")
let products = chilDic["products"]! as! NSArray
if products.count > 0
{
for item in products
{
var sr = String()
sr = (item as AnyObject) .value(forKey: "name") as! String
childrenstring.append(sr)
childrenstring.append("*")
}
majorDic.setValue(childrenstring, forKey: "Childernproducts")
}
else
{
print("products.count\(products.count)")
majorDic.setValue("NO DATA", forKey: "Childernproducts")
}
}
}
else
{
print("childernw.count\(children.count)")
majorDic.setValue("NO DATA", forKey: "Childernname")
}
}
else
{
majorDic.setValue("NO DATA", forKey: "Childernname")
majorDic.setValue("NO DATA", forKey: "Childernproducts")
}
self.globalArray.add(majorDic)
}
print("TOTAL ASSECTS\(self.globalArray)")
OperationQueue.main.addOperation({
self.tableView.reloadData()
print(self.globalArray)
print(self.detailsArray)
})
}
}).resume()
}
Try this:
var detailsArray = [DataList]()
func downloadJsonWithURL() {
let url = NSURL(string: "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2")
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
let objArr = (jsonObj?["data"] as? [[String: AnyObject]])! as NSArray
for obj in objArr {
self.detailsArray.append(DataList(json: obj as! [String : AnyObject]))
}
print(self.detailsArray)
}
}).resume()
}
Model Class
class DataList: NSObject {
var count: Int
var category_id: Int
var childern:[Children]
var name:String
init (json: [String: AnyObject]){
if let childrenList = json["children"] as? [[String: AnyObject]] {
var result = [Children]()
for obj in childrenList {
result.append(Children(json: obj))
}
self.childern = result
} else {
self.childern = [Children]()
}
if let count = json["count"] as? Int { self.count = count }
else { self.count = 0 }
if let category_id = json["category_id"] as? Int { self.category_id = category_id }
else { self.category_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
class Children:NSObject{
var count:Int
var category_id:Int
var products:[Products]
var name:String
init (json: [String: AnyObject]){
if let productList = json["products"] as? [[String: AnyObject]] {
var result = [Products]()
for obj in productList {
result.append(Products(json: obj))
}
self.products = result
} else {
self.products = [Products]()
}
if let count = json["count"] as? Int { self.count = count }
else { self.count = 0 }
if let category_id = json["category_id"] as? Int { self.category_id = category_id }
else { self.category_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
class Products:NSObject{
var product_id:Int
var name:String
init (json: [String: AnyObject]){
if let product_id = json["product_id"] as? Int { self.product_id = product_id }
else { self.product_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
NOTE: Please check your data type while parsing
I too had the same problem. Instead of using for loop try using flatMap() and then extract the value using value(forKey: " ") function
let productNames = productValues.flatMap() {$0.value}
let names = (productNames as AnyObject).value(forKey: "name")
It had worked for me for my json. My Json was similar to yours.
I got separate values in array.

Adding data to a particular table in CoreData in iOS Swift

I am using CoreData in my project and I am successfully able to save data in my tables and display. I am also able to update the existing Data. but I am not able to add a new data to a particular table.
The table relation is WorkOrderData--> one to many with WorkOrderTaskAsset and WorkOrderTaskAsset --> one to many with condition.
If I have to add a condition Object on some button click. I am not getting how to add it. I tried to create a Condition Object and add it. But I am getting error
.Condition setLabel:]: unrecognized selector sent to instance 0x600000077540'
func saveDataInCoreData(jsonArray : NSArray) {
for orders in jsonArray{
let WorkOrderDataClassName:String = String(describing: WorkOrderData.self)
let workOrderData:WorkOrderData = NSEntityDescription.insertNewObject(forEntityName: WorkOrderDataClassName, into: DatabaseController.getContext()) as! WorkOrderData
let ContractorClassName:String = String(describing: Contractor.self)
let contractor:Contractor = NSEntityDescription.insertNewObject(forEntityName: ContractorClassName, into: DatabaseController.getContext()) as! Contractor
let StatusClassName:String = String(describing: Status.self)
let status:Status = NSEntityDescription.insertNewObject(forEntityName: StatusClassName, into: DatabaseController.getContext()) as! Status
let order = orders as! NSDictionary
// Work Order Parsing
workOrderData.workOrderNo = order["workOrderNo"]! as? String
if order["description"] != nil {
workOrderData.descriptin = order["description"]! as? String
}
if order["comments"] != nil {
workOrderData.comments = order["comments"]! as? String
}
let desCodeId = order["descriptionCodeID"]! as? Int
if desCodeId != nil {
workOrderData.descriptionCodeID = Int16(UInt16(desCodeId!))
}
if order["definition"] != nil {
workOrderData.definition = order["definition"]! as? String
}
let priortyID = order["priorityID"]! as? Int
if priortyID != nil {
workOrderData.priorityID = Int16(UInt16(desCodeId!))
}
let numbrOfAssets = order["numberofAssests"]! as? Int
if numbrOfAssets != nil {
workOrderData.numberofAssests = Int16(UInt16(numbrOfAssets!))
}
if order["generatedDateTime"] != nil {
workOrderData.generatedDateTime = (order["generatedDateTime"]! as? Double)!
}
if order["initiatedBy"] != nil {
workOrderData.initiatedBy = order["initiatedBy"]! as? String
}
if order["generatedBy"] != nil {
workOrderData.generatedBy = order["generatedBy"]! as? String
}
if order["issueDate"] != nil {
workOrderData.issueDate = (order["issueDate"]! as? Double)!
}
if order["finishDate"] != nil {
workOrderData.finishDate = (order["finishDate"]! as? Double)!
}
if order["statusID"] != nil {
let statsID = order["statusID"]! as? Int
workOrderData.statusID = Int16(UInt16(statsID!))
}
if order["assigneeID"] != nil {
let assigneID = order["assigneeID"]! as? Int
workOrderData.assigneeID = Int16(UInt16(assigneID!))
}
if order["updateDate"] != nil {
let updatDate = order["updateDate"]! as? Double
workOrderData.updateDate = updatDate!
}
if order["startDate"] != nil {
workOrderData.startDate = (order["startDate"]! as? Double)!
}
if order["proceedDate"] != nil {
workOrderData.proceedDate = (order["proceedDate"]! as? Double)!
}
if order["createDate"] != nil {
workOrderData.createDate = (order["createDate"]! as? Double)!
}
if order["inclementDays"] != nil {
let inclemntDays = order["inclementDays"]! as? Int
workOrderData.inclementDays = Int16(UInt16(inclemntDays!))
}
if order["totalHydrantsPainted"] != nil {
let totalHydrantPainted = order["totalHydrantsPainted"]! as? Int
workOrderData.totalHydrantsPainted = Int16(UInt16(totalHydrantPainted!))
}
if order["totalHydrantsNotPainted"] != nil {
let totalHydrantNotPainted = order["totalHydrantsNotPainted"]! as? Int
workOrderData.totalHydrantsNotPainted = Int16(UInt16(totalHydrantNotPainted!))
}
if order["contractorId"] != nil {
let contractrId = order["contractorId"]! as? Int
workOrderData.contractorId = Int16(UInt16(contractrId!))
}
// Contractor Started
let contractorDict = order["contractor"]! as? NSDictionary
if contractorDict?["id"] != nil {
let contrctrId = contractorDict?["id"]! as? Int
contractor.id = Int16(UInt16(contrctrId!))
}
contractor.name = contractorDict?["name"]! as? String
contractor.email = contractorDict?["email"]! as? String
contractor.label = contractorDict?["label"]! as? String
contractor.purchaseOrderNumber = contractorDict?["purchaseOrderNumber"]! as? String
contractor.vendorId = contractorDict?["vendorId"]! as? String
workOrderData.contractor = contractor
if order["status"] != nil {
let statusDict = order["status"]! as? NSDictionary
let statusId = statusDict?["id"]! as? Int
if statusId != nil {
status.id = Int16(UInt16(statusId!))
}
status.label = statusDict?["label"]! as? String
status.descriptin = statusDict?["description"]! as? String
status.rule = statusDict?["rule"]! as? String
workOrderData.status = status
}
// Inclement Work Order Started
if order["workOrderInclementWeatherDates"] != nil {
let workOrderInclementWeatherDate = order["workOrderInclementWeatherDates"] as! [NSDictionary]
if workOrderInclementWeatherDate.count > 0 {
let setArray = NSMutableArray()
let set = NSMutableSet()
for inclementItem in workOrderInclementWeatherDate {
let WorkOrderInclementWeatherDatesClassName:String = String(describing: WorkOrderInclementWeatherDates.self)
let workOrderInclementWeatherDates:WorkOrderInclementWeatherDates = NSEntityDescription.insertNewObject(forEntityName: WorkOrderInclementWeatherDatesClassName, into: DatabaseController.getContext()) as! WorkOrderInclementWeatherDates
workOrderInclementWeatherDates.createTimeStamp = inclementItem.value(forKey: "createTimeStamp") as! Double
workOrderInclementWeatherDates.inclementDate = inclementItem.value(forKey: "inclementDate") as! Double
workOrderInclementWeatherDates.workOrderNo = inclementItem.value(forKey: "workOrderNo") as? String
setArray.add(workOrderInclementWeatherDates)
set.add(workOrderInclementWeatherDates)
}
workOrderData.addToWorkOrderInclementWeather(set as NSSet)
}
}
// Task List
// Inclement Work Order Started
if order["workOrderTask"] != nil {
let workOrderTaskArray = order["workOrderTask"] as! [NSDictionary]
if workOrderTaskArray.count > 0 {
let workOrderSet = NSMutableSet()
for workOrderItem in workOrderTaskArray {
let WorkOrderTaskClassName:String = String(describing: WorkOrderTask.self)
let workOrderTask:WorkOrderTask = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskClassName, into: DatabaseController.getContext()) as! WorkOrderTask
workOrderTask.woTaskDescription = workOrderItem.value(forKey: "woTaskDescription") as? String
workOrderTask.taskStatus = workOrderItem.value(forKey: "taskStatus") as? String
if workOrderItem["projectedStartDate"] != nil {
workOrderTask.projectedStartDate = workOrderItem.value(forKey: "projectedStartDate") as! Double
}
if workOrderItem["actualStartDate"] != nil {
workOrderTask.actualStartDate = workOrderItem.value(forKey: "actualStartDate") as! Double
}
if workOrderItem["taskNumber"] != nil {
let taskNumber = workOrderItem["taskNumber"]! as? Int
workOrderTask.taskNumber = Int16(UInt16(taskNumber!))
}
if workOrderItem["noOfHydrantsCompleted"] != nil {
let noOfHydrantsCompleted = workOrderItem["noOfHydrantsCompleted"]! as? Int
workOrderTask.noOfHydrantsCompleted = Int16(UInt16(noOfHydrantsCompleted!))
}
if workOrderItem["noOfHydrantsPending"] != nil {
let noOfHydrantsPending = workOrderItem["noOfHydrantsPending"]! as? Int
workOrderTask.noOfHydrantsPending = Int16(UInt16(noOfHydrantsPending!))
}
workOrderSet.add(workOrderTask)
}
workOrderData.addToWorkOrdertask(workOrderSet as NSSet)
}
}
// workOrderTaskAsstDetails
if order["workOrderTaskAsstDetails"] != nil {
let workOrderTaskAsstDetailsDict = order["workOrderTaskAsstDetails"] as! [NSDictionary]
if workOrderTaskAsstDetailsDict.count > 0 {
let set = NSMutableSet()
for workOrderTaskAsstDetailsItem in workOrderTaskAsstDetailsDict {
let WorkOrderTaskAsstDetailsClassName:String = String(describing: WorkOrderTaskAsstDetails.self)
let workOrderTaskAsstDetails:WorkOrderTaskAsstDetails = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskAsstDetailsClassName, into: DatabaseController.getContext()) as! WorkOrderTaskAsstDetails
let woTaskAsstId = workOrderTaskAsstDetailsItem["woTaskAsstId"]! as? Int
if woTaskAsstId != nil {
workOrderTaskAsstDetails.woTaskAsstId = Int16(UInt16(woTaskAsstId!))
}
workOrderTaskAsstDetails.woTaskNo = workOrderTaskAsstDetailsItem.value(forKey: "woTaskNo") as? String
workOrderTaskAsstDetails.assetId = workOrderTaskAsstDetailsItem.value(forKey: "assetId") as? String
workOrderTaskAsstDetails.descripton = workOrderTaskAsstDetailsItem.value(forKey: "description") as? String
workOrderTaskAsstDetails.statusID = workOrderTaskAsstDetailsItem.value(forKey: "statusID") as? String
if workOrderTaskAsstDetailsItem["projectedStartDate"] != nil {
workOrderTaskAsstDetails.projectedStartDate = (workOrderTaskAsstDetailsItem["projectedStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualStartDate"] != nil {
workOrderTaskAsstDetails.actualStartDate = (workOrderTaskAsstDetailsItem["actualStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["projectedCompleteDate"] != nil {
workOrderTaskAsstDetails.projectedCompleteDate = (workOrderTaskAsstDetailsItem["projectedCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualCompleteDate"] != nil {
workOrderTaskAsstDetails.actualCompleteDate = (workOrderTaskAsstDetailsItem["actualCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["lastPaintedDate"] != nil {
workOrderTaskAsstDetails.lastPaintedDate = (workOrderTaskAsstDetailsItem["lastPaintedDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["workOrderStartDate"] != nil {
workOrderTaskAsstDetails.workOrderStartDate = (workOrderTaskAsstDetailsItem["workOrderStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["createDate"] != nil {
workOrderTaskAsstDetails.createDate = (workOrderTaskAsstDetailsItem["createDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["updateDate"] != nil {
workOrderTaskAsstDetails.updateDate = (workOrderTaskAsstDetailsItem["updateDate"]! as? Double)!
}
workOrderTaskAsstDetails.workOrderNumber = workOrderTaskAsstDetailsItem.value(forKey: "workOrderNumber") as? String
workOrderTaskAsstDetails.beforePicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLatitude") as? String
workOrderTaskAsstDetails.beforePicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLongitude") as? String
workOrderTaskAsstDetails.afterPicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLatitude") as? String
workOrderTaskAsstDetails.afterPicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLongitude") as? String
let transactionType = workOrderTaskAsstDetailsItem["transactionType"]! as? Int
if transactionType != nil {
workOrderTaskAsstDetails.transactionType = Int16(UInt16(transactionType!))
}
let assetValid = workOrderTaskAsstDetailsItem["assetValid"]! as? Int
if assetValid != nil {
workOrderTaskAsstDetails.assetValid = Int16(UInt16(assetValid!))
}
//Asset
let AssetClassName:String = String(describing: Asset.self)
let asset:Asset = NSEntityDescription.insertNewObject(forEntityName: AssetClassName, into: DatabaseController.getContext()) as! Asset
let assetDict = workOrderTaskAsstDetailsItem["asset"]! as? NSDictionary
asset.descripton = assetDict?["description"]! as? String
asset.type = assetDict?["type"]! as? String
asset.assetId = assetDict?["assetId"]! as? String
if assetDict?["asset200ft"] != nil {
asset.asset200ft = assetDict?["asset200ft"]! as? String
}
if assetDict?["streetNumber"] != nil{
asset.streetNumber = assetDict?["streetNumber"]! as? String
}
asset.county = assetDict?["county"]! as? String
asset.latitude = assetDict?["latitude"]! as? String
asset.longitude = assetDict?["longitude"]! as? String
workOrderTaskAsstDetails.asset = asset
//Condition
if workOrderTaskAsstDetailsItem["assetConditions"] != nil{
let conditionDict = workOrderTaskAsstDetailsItem["assetConditions"] as! [NSDictionary]
if conditionDict.count > 0{
let conditinSet = NSMutableSet()
for assetConditionsDetailsDict in conditionDict {
let ConditionClassName:String = String(describing: Condition.self)
let condition:Condition = NSEntityDescription.insertNewObject(forEntityName: ConditionClassName, into: DatabaseController.getContext()) as! Condition
let assetConditionItem = assetConditionsDetailsDict["condition"] as! NSDictionary
condition.id = assetConditionItem["id"]as? String
condition.label = assetConditionItem["label"]as? String
condition.rule = assetConditionItem["rule"]as? String
condition.descriptin = assetConditionItem["description"]as? String
conditinSet.add(condition)
}
workOrderTaskAsstDetails.addToCondition(conditinSet as NSSet)
}
}
set.add(workOrderTaskAsstDetails)
}
workOrderData.addToWorkOrderTaskAsstDetails(set as NSSet)
}
}
// assetList
if order["assetList"] != nil {
let workOrderTaskAsstDetailsDict = order["assetList"] as! [NSDictionary]
if workOrderTaskAsstDetailsDict.count > 0 {
let set = NSMutableSet()
for workOrderTaskAsstDetailsItem in workOrderTaskAsstDetailsDict {
let WorkOrderTaskAsstDetailsClassName:String = String(describing: AssetList.self)
let workOrderTaskAsstDetails:AssetList = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskAsstDetailsClassName, into: DatabaseController.getContext()) as! AssetList
let woTaskAsstId = workOrderTaskAsstDetailsItem["woTaskAsstId"]! as? Int
if woTaskAsstId != nil {
workOrderTaskAsstDetails.woTaskAsstId = Int16(UInt16(woTaskAsstId!))
}
workOrderTaskAsstDetails.woTaskNo = workOrderTaskAsstDetailsItem.value(forKey: "woTaskNo") as? String
workOrderTaskAsstDetails.assetId = workOrderTaskAsstDetailsItem.value(forKey: "assetId") as? String
workOrderTaskAsstDetails.descripton = workOrderTaskAsstDetailsItem.value(forKey: "description") as? String
workOrderTaskAsstDetails.statusID = workOrderTaskAsstDetailsItem.value(forKey: "statusID") as? String
if workOrderTaskAsstDetailsItem["projectedStartDate"] != nil {
workOrderTaskAsstDetails.projectedStartDate = (workOrderTaskAsstDetailsItem["projectedStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualStartDate"] != nil {
workOrderTaskAsstDetails.actualStartDate = (workOrderTaskAsstDetailsItem["actualStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["projectedCompleteDate"] != nil {
workOrderTaskAsstDetails.projectedCompleteDate = (workOrderTaskAsstDetailsItem["projectedCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualCompleteDate"] != nil {
workOrderTaskAsstDetails.actualCompleteDate = (workOrderTaskAsstDetailsItem["actualCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["lastPaintedDate"] != nil {
workOrderTaskAsstDetails.lastPaintedDate = (workOrderTaskAsstDetailsItem["lastPaintedDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["workOrderStartDate"] != nil {
workOrderTaskAsstDetails.workOrderStartDate = (workOrderTaskAsstDetailsItem["workOrderStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["createDate"] != nil {
workOrderTaskAsstDetails.createDate = (workOrderTaskAsstDetailsItem["createDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["updateDate"] != nil {
workOrderTaskAsstDetails.updateDate = (workOrderTaskAsstDetailsItem["updateDate"]! as? Double)!
}
workOrderTaskAsstDetails.workOrderNumber = workOrderTaskAsstDetailsItem.value(forKey: "workOrderNumber") as? String
workOrderTaskAsstDetails.beforePicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLatitude") as? String
workOrderTaskAsstDetails.beforePicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLongitude") as? String
workOrderTaskAsstDetails.afterPicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLatitude") as? String
workOrderTaskAsstDetails.afterPicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLongitude") as? String
let transactionType = workOrderTaskAsstDetailsItem["transactionType"]! as? Int
if transactionType != nil {
workOrderTaskAsstDetails.transactionType = Int16(UInt16(transactionType!))
}
let assetValid = workOrderTaskAsstDetailsItem["assetValid"]! as? Int
if assetValid != nil {
workOrderTaskAsstDetails.assetValid = Int16(UInt16(assetValid!))
}
//Asset
let AssetClassName:String = String(describing: AssetListAsset.self)
let asset:AssetListAsset = NSEntityDescription.insertNewObject(forEntityName: AssetClassName, into: DatabaseController.getContext()) as! AssetListAsset
let assetDict = workOrderTaskAsstDetailsItem["asset"]! as? NSDictionary
asset.descripton = assetDict?["description"]! as? String
asset.type = assetDict?["type"]! as? String
asset.assetId = assetDict?["assetId"]! as? String
if assetDict?["asset200ft"] != nil {
asset.asset200ft = assetDict?["asset200ft"]! as? String
}
if assetDict?["streetNumber"] != nil{
asset.streetNumber = assetDict?["streetNumber"]! as? String
}
asset.county = assetDict?["county"]! as? String
asset.latitude = assetDict?["latitude"]! as? String
asset.longitude = assetDict?["longitude"]! as? String
workOrderTaskAsstDetails.assetListAsset = asset
//Condition
if workOrderTaskAsstDetailsItem["assetConditions"] != nil{
let conditionDict = workOrderTaskAsstDetailsItem["assetConditions"] as! [NSDictionary]
if conditionDict.count > 0{
let conditinSet = NSMutableSet()
for assetConditionsDetailsDict in conditionDict {
let ConditionClassName:String = String(describing: AssetListCondition.self)
let condition:AssetListCondition = NSEntityDescription.insertNewObject(forEntityName: ConditionClassName, into: DatabaseController.getContext()) as! AssetListCondition
let assetConditionItem = assetConditionsDetailsDict["condition"] as! NSDictionary
condition.id = assetConditionItem["id"]as? String
condition.label = assetConditionItem["label"]as? String
condition.rule = assetConditionItem["rule"]as? String
condition.descriptin = assetConditionItem["description"]as? String
conditinSet.add(condition)
}
workOrderTaskAsstDetails.addToAssetListCondition(conditinSet as NSSet)
}
}
set.add(workOrderTaskAsstDetails)
}
workOrderData.addToAssetList(set as NSSet)
}
}
DatabaseController.saveContext()
}
fetchFrmDB()
}
the code include other table also which I have not shown in pic
Please help me.. Thanks in Advance

Compiler crashes saying a variable from FIR database is unexpectedly nil, millisecs after reading the desired value

here's the function that I call that crashes:
func retrieveOtherUserData(){
profileRef.queryOrdered(byChild: "uid").queryEqual(toValue: "aRandomUserID6388").observe(.value, with:{
snapshot in
print("snapshot.value is \(snapshot.value!)")
for item in snapshot.children {
let profile = Profile(snapshot: item as! FIRDataSnapshot)
otherUID = profile!.userId!
otherUserName = profile!.firstName!
otherUserProfilePicURLString = profile!.fbDownloadURLForMediumProfPic!
}
})
}
It consistently says unexpectedly found nil when force unwrapping the profile statements. Here's what profile is referencing:
import Foundation
import UIKit
import Firebase
class Profile: NSObject {
var userId: String!
var firstName: String!
var age: Int!
var birthday: String!
var gender: String!
var education: String!
var thisIsMyFun: String!
var iAm: String!
var location: String!
var userLat: Double!
var userLong: Double!
var firStorageNameForFB1: String!
var firStorageNameForFB2: String!
var firStorageNameForFB3: String?
var firStorageNameForFB4: String?
var firStorageNameForFB5: String?
var firStorageNameForFB6: String?
var firStorageNameForFB7: String?
var firStorageNameForFB8: String?
var firStorageNameForFB9: String?
var firStorageNameForFB10: String?
var firStorageNameForPH1: String?
var firStorageNameForPH2: String?
var fbDownloadURLForSmallProfPic: String!
var fbDownloadURLForMediumProfPic: String!
var fbDownloadURLForLargeProfPic: String!
var firDownloadURLForFB1: String!
var firDownloadURLForFB2: String!
var firDownloadURLForFB3: String?
var firDownloadURLForFB4: String?
var firDownloadURLForFB5: String?
var firDownloadURLForFB6: String?
var firDownloadURLForFB7: String?
var firDownloadURLForFB8: String?
var firDownloadURLForFB9: String?
var firDownloadURLForFB10: String?
var firDownloadURLForPH1: String?
var firDownloadURLForPH2: String?
var profileKey: String!
var profileRef: FIRDatabaseReference!
init?(snapshot: FIRDataSnapshot) {
guard let dict = snapshot.value as? [String: Any] else { return nil }
guard let userId = dict["uid"] else { return nil }
guard let firstName = dict["name"] else { return nil }
guard let age = dict["age"] else { return nil }
guard let birthday = dict["birthday"] else { return nil }
guard let gender = dict["gender"] else { return nil }
guard let education = dict["education"] else { return nil }
guard let thisIsMyFun = dict["bodyOfThisIsMyFun"] else { return nil }
guard let iAm = dict["bodyOfIAM"] else { return nil }
guard let location = dict["locationOfUser"] else { return nil }
guard let userLat = dict["latitudeOfUser"] else { return nil }
guard let userLong = dict["longitudeOfUser"] else { return nil }
guard let firStorageNameForFB1 = dict["firStorageNameForFBPhoto1"] else { return nil }
guard let firStorageNameForFB2 = dict["firStorageNameForFBPhoto2"] else { return nil }
guard let firStorageNameForFB3 = dict["firStorageNameForFBPhoto3"] else { return nil }
guard let firStorageNameForFB4 = dict["firStorageNameForFBPhoto4"] else { return nil }
guard let firStorageNameForFB5 = dict["firStorageNameForFBPhoto5"] else { return nil }
guard let firStorageNameForFB6 = dict["firStorageNameForFBPhoto6"] else { return nil }
guard let firStorageNameForFB7 = dict["firStorageNameForFBPhoto7"] else { return nil }
guard let firStorageNameForFB8 = dict["firStorageNameForFBPhoto8"] else { return nil }
guard let firStorageNameForFB9 = dict["firStorageNameForFBPhoto9"] else { return nil }
guard let firStorageNameForFB10 = dict["firStorageNameForFBPhoto10"] else { return nil }
guard let firStorageNameForPH1 = dict["firStorageNameForPHPhoto1"] else { return nil }
guard let firStorageNameForPH2 = dict["firStorageNameForPHPhoto2"] else { return nil }
guard let fbDownloadURLForSmallProfPic = dict["URLofSmallFBProfPic"] else { return nil }
guard let fbDownloadURLForMediumProfPic = dict["URLofMediumFBProfPic"] else { return nil }
guard let fbDownloadURLForLargeProfPic = dict["URLofLargeFBProfPic"] else { return nil }
guard let firDownloadURLForFB1 = dict["firDownloadURLStringForFBPic1"] else { return nil }
guard let firDownloadURLForFB2 = dict["firDownloadURLStringForFBPic2"] else { return nil }
guard let firDownloadURLForFB3 = dict["firDownloadURLStringForFBPic3"] else { return nil }
guard let firDownloadURLForFB4 = dict["firDownloadURLStringForFBPic4"] else { return nil }
guard let firDownloadURLForFB5 = dict["firDownloadURLStringForFBPic5"] else { return nil }
guard let firDownloadURLForFB6 = dict["firDownloadURLStringForFBPic6"] else { return nil }
guard let firDownloadURLForFB7 = dict["firDownloadURLStringForFBPic7"] else { return nil }
guard let firDownloadURLForFB8 = dict["firDownloadURLStringForFBPic8"] else { return nil }
guard let firDownloadURLForFB9 = dict["firDownloadURLStringForFBPic9"] else { return nil }
guard let firDownloadURLForFB10 = dict["firDownloadURLStringForFBPic10"] else { return nil }
guard let firDownloadURLForPH1 = dict["firDownloadURLStringForPHPic1"] else { return nil }
guard let firDownloadURLForPH2 = dict["firDownloadURLStringForPHPic2"] else { return nil }
self.userId = userId as! String
self.firstName = firstName as! String
self.age = age as! Int
self.birthday = birthday as! String
self.gender = gender as! String
self.education = education as! String
self.thisIsMyFun = thisIsMyFun as! String
self.iAm = iAm as! String
self.location = location as! String
self.userLat = userLat as! Double
self.userLong = userLong as! Double
self.firStorageNameForFB1 = firStorageNameForFB1 as! String
self.firStorageNameForFB2 = firStorageNameForFB2 as! String
self.firStorageNameForFB3 = firStorageNameForFB3 as? String
self.firStorageNameForFB4 = firStorageNameForFB4 as? String
self.firStorageNameForFB5 = firStorageNameForFB5 as? String
self.firStorageNameForFB6 = firStorageNameForFB6 as? String
self.firStorageNameForFB7 = firStorageNameForFB7 as? String
self.firStorageNameForFB8 = firStorageNameForFB8 as? String
self.firStorageNameForFB9 = firStorageNameForFB9 as? String
self.firStorageNameForFB10 = firStorageNameForFB10 as? String
self.firStorageNameForPH1 = firStorageNameForPH1 as? String
self.firStorageNameForPH2 = firStorageNameForPH2 as? String
self.fbDownloadURLForSmallProfPic = fbDownloadURLForSmallProfPic as! String
self.fbDownloadURLForMediumProfPic = fbDownloadURLForMediumProfPic as! String
self.fbDownloadURLForLargeProfPic = fbDownloadURLForLargeProfPic as! String
self.firDownloadURLForFB1 = firDownloadURLForFB1 as! String
self.firDownloadURLForFB2 = firDownloadURLForFB2 as! String
self.firDownloadURLForFB3 = firDownloadURLForFB3 as? String
self.firDownloadURLForFB4 = firDownloadURLForFB4 as? String
self.firDownloadURLForFB5 = firDownloadURLForFB5 as? String
self.firDownloadURLForFB6 = firDownloadURLForFB6 as? String
self.firDownloadURLForFB7 = firDownloadURLForFB7 as? String
self.firDownloadURLForFB8 = firDownloadURLForFB8 as? String
self.firDownloadURLForFB9 = firDownloadURLForFB9 as? String
self.firDownloadURLForFB10 = firDownloadURLForFB10 as? String
self.firDownloadURLForPH1 = firDownloadURLForPH1 as? String
self.firDownloadURLForPH2 = firDownloadURLForPH2 as? String
}
}
For some reason doing virtually the same thing when accessing a specific set of filters worked. Here's the working version of a very similar task and instruction:
var filterSet:FilterSet!
override func viewDidLoad() {
super.viewDidLoad()
filterSetRef.queryOrdered(byChild: "uid").queryEqual(toValue: "aRandomUserID6388").observe(.value, with:{snapshot
in
print("snapshot.value is \(snapshot.value!)")
for item in snapshot.children {
let filterSet = FilterSet(snapshot: item as! FIRDataSnapshot)
ageRangeFilterDeclined = filterSet!.declinedAgeRange!
maxAgeMatch = filterSet!.maxAge!
minAgeMatch = filterSet!.minAge!
genderPref = filterSet!.genderPreference!
includeFBFriendsInMatchResults = filterSet!.includeFBFriends!
includeSportingEvents = filterSet!.sportingEvents!
includeHiking = filterSet!.hiking!
includeMiscellaneous = filterSet!.misc!
includeMuseumsOrArtGalleries = filterSet!.museumsAndArtGalleries!
includePlayMusic = filterSet!.music!
includePlaySports = filterSet!.playingSports!
includeStudyPartner = filterSet!.studyPartner!
includeDancing = filterSet!.dancing!
includeTheatre = filterSet!.theatre!
includeConcerts = filterSet!.concerts!
includeRunningBuddy = filterSet!.running!
includeGames = filterSet!.games!
maxDistanceFilterDeclined = filterSet!.maxDistanceDeclined!
maxDistance = filterSet!.maximumDistance!
}
})
}
}
Here's the FilterSet class that gets successfully populated then referenced, unlike what happens with the Profile class:
import UIKit
import Firebase
class FilterSet: NSObject{
var uID: String!
var declinedAgeRange: Bool!
var genderPreference: String!
var includeFBFriends: Bool!
var sportingEvents: Bool!
var hiking: Bool!
var misc: Bool!
var museumsAndArtGalleries: Bool!
var music: Bool!
var playingSports: Bool!
var running: Bool!
var studyPartner: Bool!
var dancing: Bool!
var theatre: Bool!
var concerts: Bool!
var games: Bool!
var maxDistanceDeclined: Bool!
var maximumDistance: Int!
var maxAge: Int!
var minAge: Int!
var filterSetKey: String!
var filterRef: FIRDatabaseReference!
init?(snapshot: FIRDataSnapshot) {
guard let dict = snapshot.value as? [String: Any] else
{ return nil }
guard let uID = dict["uid"] else { return nil }
guard let declinedAgeRange = dict["DeclinedAgeRangeFilter"] else
{ return nil }
guard let genderPreference = dict["GenderPreference"] else
{ return nil }
guard let includeFBFriends = dict["IncludeFBFriendsInMatches"] else
{ return nil }
guard let sportingEvents = dict["IncludeAttendSportingEvent"] else
{ return nil }
guard let hiking = dict["IncludeHikingPartner"] else
{ return nil }
guard let misc = dict["IncludeMiscellaneous"] else
{ return nil }
guard let museumsAndArtGalleries =
dict["IncludeMuseumsAndArtGalleries"] else { return nil }
guard let music = dict["IncludePlayingMusic"] else { return nil }
guard let playingSports = dict["IncludePlayingSports"] else
{ return nil }
guard let running = dict["IncludeRunningBuddy"] else
{ return nil }
guard let studyPartner = dict["IncludeStudyPartner"] else
{ return nil }
guard let dancing = dict["IncludeDancing"] else { return nil }
guard let concerts = dict["IncludeConcerts"] else { return nil }
guard let theatre = dict["IncludeTheatre"] else { return nil }
guard let games = dict["IncludeGames"] else { return nil }
guard let maxDistanceDeclined =
dict["MaxDistanceFilterDeclined"] else { return nil }
guard let maximumDistance = dict["MaxDistanceOfPostings"] else
{ return nil }
guard let maxAge = dict["MaximumMatchAge"] else
{ return nil }
guard let minAge = dict["MinimumMatchAge"] else { return nil }
self.uID = uID as! String
self.declinedAgeRange = declinedAgeRange as! Bool
self.genderPreference = genderPreference as! String
self.includeFBFriends = includeFBFriends as! Bool
self.sportingEvents = sportingEvents as! Bool
self.hiking = hiking as! Bool
self.misc = misc as! Bool
self.museumsAndArtGalleries = museumsAndArtGalleries as! Bool
self.music = music as! Bool
self.playingSports = playingSports as! Bool
self.running = running as! Bool
self.studyPartner = studyPartner as! Bool
self.dancing = dancing as! Bool
self.concerts = concerts as! Bool
self.theatre = theatre as! Bool
self.games = games as! Bool
self.maxDistanceDeclined = maxDistanceDeclined as! Bool
self.maximumDistance = maximumDistance as! Int
self.maxAge = maxAge as! Int
self.minAge = minAge as! Int
}
}
I also tried to extract the data from FIR Database using:
if let dict = snapshot.value as? Dictionary<String, AnyObject> {
otherUserName = dict["userName"], etc.
The compiler tells me the desired values are present and readable milliseconds before then crashing upon saying it unexpectedly found a nil value for "profile!userId!" or whichever of the three profile statements I have it read first. (I edit out the extraneous values it also said were in this snapshot):
snapshot.value is {
"-Khh__kC9V9mnT1SAbGh" = {
URLofMediumFBProfPic = "https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/10665301_10204284275524944_7824974439027842885_n.jpg?oh=237544b1350b5759e963c2f5b8234f69&oe=594E1F1";
name = Michael;
uid = aRandomUserID6388;
};
}
I also tried to have these values read after implementing a 3-second delay, but that didn't work.
I don't see any differences between my working code and my non-working code. I am out of ideas for how to solve this problem. Anyone have any idea how my working and non-working examples differ? Sorry for there being so much code above...
changing the profile object to:
init?(snapshot: FIRDataSnapshot) {
let dict = snapshot.value as! [String: Any]// else { return nil }
let userId = dict["uid"] as! String// else { return nil }
let firstName = dict["name"] as! String //else { return nil }
let age = dict["age"] as! Int //else { return nil }
let birthday = dict["birthday"] as! String //else { return nil }
let gender = dict["gender"] as! String //else { return nil }
let education = dict["education"] as! String //else { return nil }
let thisIsMyFun = dict["bodyOfThisIsMyFun"] as! String // else { return nil }
let iAm = dict["bodyOfIAM"] as! String //else { return nil }
let location = dict["locationOfUser"] as! String //else { return nil }
let userLat = dict["latitudeOfUser"] as! Double //else { return nil }
let userLong = dict["longitudeOfUser"] as! Double //else { return nil }
let firStorageNameForFB1 = dict["firStorageNameForFBPhoto1"] as! String //else { return nil }
let firStorageNameForFB2 = dict["firStorageNameForFBPhoto2"] as! String //else { return nil }
self.firStorageNameForFB3 = dict["firStorageNameForFBPhoto3"] as? String
self.firStorageNameForFB4 = dict["firStorageNameForFBPhoto4"] as? String
self.firStorageNameForFB5 = dict["firStorageNameForFBPhoto5"] as? String
self.firStorageNameForFB6 = dict["firStorageNameForFBPhoto6"] as? String
self.firStorageNameForFB7 = dict["firStorageNameForFBPhoto7"] as? String
self.firStorageNameForFB8 = dict["firStorageNameForFBPhoto8"] as? String
self.firStorageNameForFB9 = dict["firStorageNameForFBPhoto9"] as? String
self.firStorageNameForFB10 = dict["firStorageNameForFBPhoto10"] as? String
self.firStorageNameForPH1 = dict["firStorageNameForPHPhoto1"] as? String
self.firStorageNameForPH2 = dict["firStorageNameForPHPhoto2"] as? String
let fbDownloadURLForSmallProfPic = dict["URLofSmallFBProfPic"] as! String//else { return nil }
let fbDownloadURLForMediumProfPic = dict["URLofMediumFBProfPic"] as! String//else { return nil }
let fbDownloadURLForLargeProfPic = dict["URLofLargeFBProfPic"] as! String// else { return nil }
let firDownloadURLForFB1 = dict["firDownloadURLStringForFBPic1"] as! String// else { return nil }
let firDownloadURLForFB2 = dict["firDownloadURLStringForFBPic2"] as! String// else { return nil }
self.firDownloadURLForFB3 = dict["firDownloadURLStringForFBPic3"] as? String
self.firDownloadURLForFB4 = dict["firDownloadURLStringForFBPic4"] as? String
self.firDownloadURLForFB5 = dict["firDownloadURLStringForFBPic5"] as? String
self.firDownloadURLForFB6 = dict["firDownloadURLStringForFBPic6"] as? String
self.firDownloadURLForFB7 = dict["firDownloadURLStringForFBPic7"] as? String
self.firDownloadURLForFB8 = dict["firDownloadURLStringForFBPic8"] as? String
self.firDownloadURLForFB9 = dict["firDownloadURLStringForFBPic9"] as? String
self.firDownloadURLForFB10 = dict["firDownloadURLStringForFBPic10"] as? String
self.firDownloadURLForPH1 = dict["firDownloadURLStringForPHPic1"] as? String
self.firDownloadURLForPH2 = dict["firDownloadURLStringForPHPic2"] as? String
self.activePostID1 = dict["FirstActivePostID"] as? String
self.activePostID2 = dict["SecondActivePostID"] as? String
self.activePostID3 = dict["ThirdActivePostID"] as? String
self.activePostID4 = dict["FourthActivePostID"] as? String
self.activePostID5 = dict["FifthActivePostID"] as? String
self.activePostID6 = dict["SixthActivePostID"] as? String
self.userId = userId as! String
self.firstName = firstName as! String
self.age = age as! Int
self.birthday = birthday as! String
self.gender = gender as! String
self.education = education as! String
self.thisIsMyFun = thisIsMyFun as! String
self.iAm = iAm as! String
self.location = location as! String
self.userLat = userLat as! Double
self.userLong = userLong as! Double
self.firStorageNameForFB1 = firStorageNameForFB1 as! String
self.firStorageNameForFB2 = firStorageNameForFB2 as! String
self.firStorageNameForFB3 = firStorageNameForFB3 as? String
self.firStorageNameForFB4 = firStorageNameForFB4 as? String
self.firStorageNameForFB5 = firStorageNameForFB5 as? String
self.firStorageNameForFB6 = firStorageNameForFB6 as? String
self.firStorageNameForFB7 = firStorageNameForFB7 as? String
self.firStorageNameForFB8 = firStorageNameForFB8 as? String
self.firStorageNameForFB9 = firStorageNameForFB9 as? String
self.firStorageNameForFB10 = firStorageNameForFB10 as? String
self.firStorageNameForPH1 = firStorageNameForPH1 as? String
self.firStorageNameForPH2 = firStorageNameForPH2 as? String
self.fbDownloadURLForSmallProfPic = fbDownloadURLForSmallProfPic as! String
self.fbDownloadURLForMediumProfPic = fbDownloadURLForMediumProfPic as! String
self.fbDownloadURLForLargeProfPic = fbDownloadURLForLargeProfPic as! String
self.firDownloadURLForFB1 = firDownloadURLForFB1 as! String
self.firDownloadURLForFB2 = firDownloadURLForFB2 as! String
self.firDownloadURLForFB3 = firDownloadURLForFB3 as? String
self.firDownloadURLForFB4 = firDownloadURLForFB4 as? String
self.firDownloadURLForFB5 = firDownloadURLForFB5 as? String
self.firDownloadURLForFB6 = firDownloadURLForFB6 as? String
self.firDownloadURLForFB7 = firDownloadURLForFB7 as? String
self.firDownloadURLForFB8 = firDownloadURLForFB8 as? String
self.firDownloadURLForFB9 = firDownloadURLForFB9 as? String
self.firDownloadURLForFB10 = firDownloadURLForFB10 as? String
self.firDownloadURLForPH1 = firDownloadURLForPH1 as? String
self.firDownloadURLForPH2 = firDownloadURLForPH2 as? String
self.activePostID1 = activePostID1 as? String
self.activePostID2 = activePostID2 as? String
self.activePostID3 = activePostID3 as? String
self.activePostID4 = activePostID4 as? String
self.activePostID5 = activePostID5 as? String
self.activePostID6 = activePostID6 as? String
}
This results in the original crashing function creating optional values that when forced unwrapped give me the desired values. Not sure why exactly the variables are defined as optional values given that they were defined as non-optional type. Regardless, this somehow solved my problem of not being able to extract needed values.
Look at the init of Profile. You expect optional values (like firStorageNameForFB3) but you are using
guard let firStorageNameForFB3 = dict["firStorageNameForFBPhoto3"] else { return nil }
So every time firStorageNameForFB3 is nil; profile will also be nil.
Try change the init of optional values in your model to:
init?(snapshot: FIRDataSnapshot) {
// ...
self.firStorageNameForFB3 = dict["firStorageNameForFBPhoto3"] as? String
// ...
}
and remove the guard let for this values.

Resources