FMDB - How can I assign query result to variable? - ios

I'm using FMDB module to work with SQLite in my swift project.
Now I can add new records to database. But also I want to show some query results in textField or even in label.
Here's my part of code that I'm trying to use. But it doesn't works.
Please help me
DataBaseModel.swift:
func getElectr100() -> String {
sharedInstance.database?.open()
let tarElectr100:FMResultSet! = sharedInstance.database!.executeQuery("SELECT tarif_value FROM tarifs WHERE tarif_name = ?", withArgumentsIn: ["electr100"])
sharedInstance.database!.close()
let resultItem = String(describing: tarElectr100)
print(resultItem)
return resultItem
}
ViewController.swift:
resultLabel.text = databaseModel.getElectr100(????)
What should I write in ViewController.swift to get the value? How to do it correctly?

Related

Filtering Realm object returns nil when there is a 100% value

I am stucked in situation when I am trying to .filter Realm objects with predicate and it returns nil, but I do the same query in Realm studio and it DOES work there.
I can return idFolder, but can't query the object using it
folders = realm.objects(Folder.self)
currentFolder = String(describing: folders?.first?.idFolder)
My code of querying:
if let idFolder = currentFolder {
let folderName = folders?.filter("idFolder = '\(String(describing: idFolder))'").first?.name
let name = callAlert(title: "Add new well for folder \(String(describing: folderName))")
}
The problem is that folderName = nil
I double checked the value of currentFolder and it is equal to what I have in my Realm database. Here is a screenshot:
Realm database
Does anybody know what I am doing wrong?
I also tried to use new querying instead of chaining request, didn't work.
the problem is on the query
"idFolder = '\(String(describing: idFolder))'"
the correct one should be like that
update
"idFolder == \(idFolder)"

search a particular record in table view controller iOS swift

I am fetching data from url using jsonserialization method and stores each and every record in an object of a class and displays each record in table vc.
Now I want to implement search using search bar and watch many tutorials which had comparison between array of string type and another array of string type(Hardcoded values in array).
But according to my need, my data is store in class obj not hardcoded data and data from that object is displayed on cellforrow.
cellforrow contains.
if isSearching
{
cell.textLabel?.text = searchArray[indexPath.row] //.compName
cell.detailTextLabel?.text = searchArray[indexPath.row]
}
else{
cell.textLabel?.text = tempArray[indexPath.row].compName
cell.detailTextLabel?.text = tempArray[indexPath.row].complocation
}
return cell
So how to implement search bar, getting following error.
kindly help!
here my classname is -> comp.
and searchArray is array of strings and
tempArray is array which contains class obj
Image of the error
Found it. here's it is
following is change in else condition
searchArr = tempArray.filter { $0.<classAttribute>.contains(searchText) }
searchArray = searchArr as! [comp]
print("search match")
listTableView.reloadData()
here searchArr and searchArray and tempArray are array of class type, &
classAttribute is ATTRIBUTE of that class that you want to search in tableview, my class name is "comp"
Then you just have to modify search filter you use to be:
searchArray = tempArray.filter({$0.compName == searchBarClicked.text!})
Compiler was telling you that you cannot compare $0 which is of type comp to searchBarClicked.text which is String, so $0.compName will be String and thus == can be used
Use this:
searchArray = searchArray.filter{(($0["name"]?.localizedCaseInsensitiveContains(textField.text!)))!}

FirebaseDatabase query issues in Swift

So I am currently working on a clone like snapchat and I am sending pull requests to the server, but as for downloading, it is not going so well. I created a reference to the database that looks like this,
var recievers: FIRDatabaseReference{
return mainRef.child("pullRequests")
}
and then I have a viewController that parses the data (which I know isn't the best way to go about this but I'm just trying to get it working right now) and in there I have this
DataService.instance.recievers.observeSingleEvent(of: .value) {(recipients: FIRDataSnapshot) in
if let recipient = recipients.value as? Dictionary<String,AnyObject>{
var index = 0;
for(key,value) in recipient{
index = index+1
if let dict = value as? Dictionary<String,AnyObject>{
if let reciever = dict["recipents"] as? Dictionary<String,AnyObject>{
if let num = reciever["\(index)"] as? String{
let uid = num
recipientsArr.append(uid)
}
}
}
}
}
}
for i in 0...recipientsArr.count{
print(i)
}
I'm not getting any compiling errors but it is also not adding anything into the recipientsArr, can anyone help guide me in the right direction?
My Firebase looks like this:
You're not decoding the snapshot properly. Its unclear from your question what is the value event you want to observe - is it just a new recipient that was added? the whole pullRequest?
In any case you're observing the pullRequest reference and therefore in order to decode the snapshot:
if let pullRequest = recipients.value as? Dictionary<String,AnyObject>{
if let recipientsList = pullRequest["recipents"] as? Dictionary<String,AnyObject>{
for (_, value) in recipientsList {
if let uid = value as? String{
recipientsArr.append(uid)
}
}
}
}
The problem is that you are using the method observeSingleEvent to update the value in the database, when this method is only used to recieve data from the database, not updated. In other words, it read-only.
The way to update record in a firebase database works different than the read methods. You can use both methods setValue and updateChildValues to perform updates. They both work on a database reference.
To use the setValue method, you should do something like this. I'll assume that you already have a pullRequests object that you previously created from the information you fetched from the database and have it in a variable:
let previousRecipents = pullRequests.recipents
let allRecipents = previousRecipents.append(newRecipent) // Assuming preivousRecipents is an array and you have the new Recipent
recievers.child("recipents").setValue(allRecipents)
To use the updateChildValues, it works very similar.
let previousRecipents = pullRequests.recipents
let allRecipents = previousRecipents.append(newRecipent) // Assuming preivousRecipents is an array and you have the new Recipent
let parametersToUpdate = ["recipents": allRecipents]
recievers.updateChildValues(parametersToUpdate)
For further information on how to update, check the following link:
https://firebase.google.com/docs/database/ios/save-data
Hope it helps!

Firebase data comparison swift

hi I'm new to swift and i'm using firebase in my app. i want to get all the data under a child from firebase database and compare it with an already existing array to find the missing values and load them in tableview i had added the code i use to perform this and in that the for loop is called every time when new child is found and i want to perform that for loop after getting all the values from the firebase database. is there any way to perform this or is there any way to know whether the firebase had retrieved all the data. Thanks in advance
func fetchUsers()
{
ingredientMasterArr.removeAll()
refhandle1 = ref.child("ingredients").observeEventType(.ChildAdded, withBlock:
{ (snapshot) in
if let dictionary = snapshot.value as? [String : String]
{
let ingredients = IngredientsClass()
ingredients.id = dictionary["id"]
ingredients.ingredient_name = dictionary["ingredient_name"]
// ingredients.category
ingredientMasterArr.append(ingredients)
}
FilteredIngMasterArr.removeAll()
let temp = IngredientsClass()
for MasterID in ingredientMasterArr
{
if (ShopIngKeysArr .contains(MasterID.id!)){
print("if",MasterID.ingredient_name)
}
else
{
print("else",MasterID.ingredient_name)
temp.id = MasterID.id
temp.ingredient_name = MasterID.ingredient_name
FilteredIngMasterArr.append(temp)
}
}
self.tbl_ingMaster.reloadData()
})
}
Using the .Value event type instead of .ChildAdded should give you all the results at once:
refhandle1 = ref.child("ingredients").observeEventType(.Value, ...
Read the firebase documentation on retrieving data for more details.

How to get a list of column names with Sqlite.swift?

For debugging purposes I am trying to get a simple list of the column names in my SQLite table. I am using the SQLite.swift framework.
My question is more specific than How to get a list of column names on sqlite3 / iPhone? so I am creating a new question.
Using
try db.execute("PRAGMA table_info(table_name);")
by applying this answer to the documentation didn't work for me (nothing happened).
Assuming you already have a database connection called db set up, to get a list of the column names, you can use the following code:
do {
let tableInfo = Array(try db.prepare("PRAGMA table_info(table_name)"))
for line in tableInfo {
print(line[1]!, terminator: " ")
}
print()
} catch _ { }
where table_name is replaced with the literal string of your table's name.
You can also add
print(tableInfo)
to see more pragma info about your table.
Credits
Thanks to this answer for clues of how to do this.
Example Function
Tested routine from Joe Blow to save a little typing:
func findColumns(_ tableName:String) {
var asAnArray:[String] = []
do {
let s = try db!.prepare("PRAGMA table_info(" + tableName + ")" )
for row in s { asAnArray.append(row[1]! as! String) }
}
catch { print("some woe in findColumns for \(tableName) \(error)") }
let asAString = asAnArray.joined(separator: ",")
print(asAnArray)
print(asAString)
}

Resources