How do you retrieve data from Firebase that has been manually entered? - swift

I'm creating a new iOS app for a lacrosse team. I've manually added a registrationCode into my Firebase database.
I've tried getting a reference to the database and then using the .observe method to get the value but it crashes.
My latest code attempt:
let rootRef = Database.database().reference().child("groove-lacrosse")
rootRef.observe(.value, with: {snapshot in
print(snapshot.value as Any)
})
What's the correct way, programmatically, to retrieve Firebase data that was manually entered?
The image is the Firebase entry

It looks like groove-lacrosse is the name of your database, in which case you don't need to specify that anywhere.
Instead you can just read the registration code directly and then print its value:
let rootRef = Database.database().reference().child("registrationCode")
rootRef.observe(.value, with: {snapshot in
print(snapshot.value as Any)
})

Related

How to reset intent extension configurations in WidgetKit

I have an application where a user can login. If a user is logged in, then I display a placeholder for my widget and it's configurable through an intent extension.
The configuration has two options:
the first option depends on the username of the user currently logged in.
the second option depends on the value of the first option.
This works fine for 1 user, however, if the user logs out, then logs in with a different account, the old selected options are still selected when they try to configure the widget, which are wrong options since it's now a different user. Also, the old data is still shown in the widget.
How do I reset the configuration of a widget in WidgetKit? Meaning, when the user tries to configure it all the previous configurations would be unselected and empty.
I tried
WidgetCenter.shared.reloadAllTimelines()
But that only reloads the timeline methods but does not reset configurations.
I've looked at Apple's documentations and could not find anything about it either.
You can't. The only option you have is to ignore the configuration option on the widget side and show some kind of error message to the user that their config needs to be updated. INExtension does not provide a way to handle this (yet).
I found this solution, but for dynamic properties only: use different identifiers for every user in your IntentHandler.
Example:
class IntentHandler: XXExtension { ... }
extension IntentHandler: XXDynamicXXXSelectionIntentHandling {
func provideXXXOptionsCollection(for intent: XXDynamicXXXSelectionIntent, with completion: #escaping (XXObjectCollection<XXX>?, Error?) -> Void) {
let userId = (UserDefaults.myGroup().object(forKey: "UserId" ) as? String) ?? ""
let items: [XXX] = UserDefaults.myGroup().sharedXxx.map { (sharedXxx) -> XXX in
return XXX(identifier: userId + "_" + sharedXxx.Id // <== add unique prefix ===
display: sharedXxx.visibleName())
}
let collection = XXObjectCollection(items: items)
completion(collection, nil)
}
}
I had the same issue that the widget was showing stale configuration options. I solved this by forcefully refreshing all objects in my shared Core Data database which I was using. I did this in the „getTimeline“ method.

Swift - Read Google Sheets

I'm working on an app that uses Google Sheets as a database, but I can't figure out how to get Swift to read from google sheets. I've looked through the API website and a few questions on here but I need some help just getting started. So far I have;
private let scopes = [kGTLRAuthScopeSheetsSpreadsheets]
private let service = GTLRSheetsService()
var range = "Form Responses 1!A1:D3"
let spreadsheetId = "p;;;;;;p;;;;;;;;1LqXa6v75JE8RQQDOI4Z_g8mUT8x0DhsEDwRIaxDN-DU" // Portfolio
let query = GTLRSheetsQuery_SpreadsheetsValuesGet.query(withSpreadsheetId: spreadsheetId, range:range)
service.executeQuery(query, delegate: self, didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
Which I got from another question on here...
But 'displayResultWithTicket' is an unresolved identifier. Currently it gets to the last line, and debugging I'm not even sure what to do with the 'query' value. I'm really not even sure if it's reading the correct spreadsheet. How can I tell?
Long story short, I'm lost.
I recently made an app that uses Google Sheets. But I used the CSV file for the database. This might help. If you want, I can share the details.
First you need to export the Google Sheets file in CSV format. I used Realm to read CSV. Using Realm Studio, you need to create the columns as in the CSV file. Then you can import the CSV file into Realm Studio. Your database is ready.
In didFinishLaunchingWithOptions to find the file created after installing Realm on your project
print(Realm.Configuration.defaultConfiguration.fileURL!.path)
Now we will use the database with Swift.
For this, we must first add the Realm file that we prepared to the XCode project directory. Then we use it in ViewController this way to get data.
var realm : Realm!
For get the data in default.realm file
let realmPath = Bundle.main.url(forResource: "default", withExtension: "realm")!
let realmConfiguration = Realm.Configuration(fileURL: realmPath, readOnly: true)
do{
realm = try Realm(configuration: realmConfiguration)
}
catch {
print("error \(error.localizedDescription)")
}
You can export the result to an array. I hope it helps.

Search user engine with Firebase

I want to implement a search user engine on my app. It is writen with swift and has a Firebase backend. The problem is that I don't find any help on the web.
My data is structured like this:
https://i.stack.imgur.com/N7qbT.png
I tried with this code and others, but still don't working:
Database.database().reference().queryOrdered(byChild: "fullname").queryEqual(toValue: "michel dupond").observe(.childAdded, with: { (snapshot) in
print("Snapshot:", snapshot as? [String: String])
}
Will your search always contain a full name? If you want to implement something like contains(value: String) I'd recommend using Algolia to add string searches.

Swift Vapor Fluent updating an existing row

I know you can do Model.delete() and Model.save()
Is there a way to update an existing row?
In Fluent 2.0 there is a property added to every Entity/Model:
let storage = Storage()
This object is holding additional information for each entity, if storage.exists is true it will update data when you call save() instead of trying to insert new item to database.
Reading Fluent's code, I believe it saves the fields that are "dirty".
So, you would have to do something like this:
let user = try User.find(42)
user.name = "Other Name"
try user.save()
I didn't try this, but I'll do it soon.

how to save related core data objects to parse with swift

My app is a simple word list sharing app. There are entities of Owners who own entities Wordlists with entities of related words in CoreData. In one screen I want to be able to save a wordList and its related words and owner to Parse on the push of a button. Then in another screen I want to be able to download a WordList and its related words, then save it to core data. present the name of the list in a table. The code I have is:
// To save the wordList to Parse:
#IBAction func shareWordList(sender: AnyObject) {
let parseWordList = PFObject(className: "WordList")
parseWordList.setObject("\(wordList?.listName)", forKey: "ListName")
parseWordList.setObject("\(wordList?.owner)", forKey: "Owner")
parseWordList.setObject("\(wordList?.words)", forKey: "Words")
parseWordList.setObject("\(wordList?.isSharedDate)", forKey: "IsSharedDate")
parseWordList.setObject("\(wordList?.isShared)", forKey: "IsShared")
parseWordList.setObject("\(wordList?.createdDate)", forKey: "CreatedDate")
parseWordList.setObject("\(wordList?.isAppList)", forKey: "IsAppList")
parseWordList.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
print("object uploaded")
} else {
print("Error: \(error) \(error?.userInfo)")
}
}
This uploads ok for most items, but the words and owner related to the wordList are not saving.
Is it possible to use the relationship properties like this with Parse? How would I then get a shared wordList and all its properties back from Parse into CoreData?
Thanks in advance to anyone for some help with this....
This code "\(wordList?.words)" is getting the human readable description of the relationship contents. That is a log description of the NSSet of managed objects. That's why you get basically gibberish in the parse data store.
What you really want to do is to get the relationship and then ask for the name of each item. You can do that with KVC. When you have that it would be an NSSet of strings that you can use to store directly.
Arguably it would be better to have multiple different classes in the parse data store which match the entities in your core data model. If you do that then you can process the relationship items to create new objects in the parse data store and then add them (once saved) to parse relationships.
It's also possible to use the REST interface to parse with a library like RestKit to map from your parse data store contents directly into core data.