In my iOS project, I am using Firebase to create a real time database. I have already imported it in the AppDelegate.swift.
When trying to reference my database within the app, an error appears.
Any ideas on how to fix this? Here is the code:
import UIKit
import Firebase
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
post()
}
func post(){
let title = "Title"
let message = "Message"
let post : [String : AnyObject] = ["title" : title as AnyObject,
"message" : message as AnyObject]
let databaseRef = FirebaseApp.database().reference()
databaseRef.child("Posts").childByAutoId().setValue(post)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to first configure firebase, example:
FirebaseApp.configure()
then you can reference to the database:
let databaseRef = Database.database().reference()
FirebaseApp does not contain a method called database()
If your Firebase/Database version is 4.9.0, the following should give you a good start.
import UIKit
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override init() {
super.init()
FirebaseApp.configure()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
}
import UIKit
import FirebaseDatabase
class TableViewController: UITableViewController {
// MARK: - Instance variables
var databaseRef: DatabaseReference!
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
//getting a reference to the node artists
databaseRef = Database.database().reference()
}
}
Add 'Firebase/Database' to your pods:
pod 'Firebase/Core'
pod 'Firebase/Database'
Then update the pods
pod install
Into your code be sure to import firebase
import Firebase
And use it as
FirebaseApp.configure()
var ref: DatabaseReference!
ref = Database.database().reference()
ref.setValue("Testing")
More info on Firebase help
Related
This time, I am implementing the screen with RxSwift / MVVM.
It's too difficult to implement RxSwift as an MVVM.
What I wanted to ask you was to enter the list screen and get the data.
Then it went into the detail screen and changed specific data.
And if it go to the list screen, it have to update the data.
I think I can put data in the viewwillappear() of the view controller, and I do not know how to implement the renewal in the view Model, and I do not know if it is right to do this in functional programming like rx.
I defined the viewmodel as follows.
The store.getListEventWinning() method is a function that fits data and is delivered in the form of Observable.
Binding was done in view controller as below.
You don't give a lot of detail, despite the code you posted. I will address your specific comment, "What I wanted to ask you was to enter the list screen and get the data. Then it went into the detail screen and changed specific data. And if it go to the list screen, it have to update the data."
Using my CLE library (which you can install with cocoapods or SPM) doing this is quite simple.
let change = changeButton.rx.tap
.flatMapFirst(presentScene(animated: true) {
DetailViewController.scene { $0.connect() }
})
Here is a complete example that you can run yourself to see how it works. To run the below, just add XIB files for the two view controllers, and hook up the outlets.
import Cause_Logic_Effect
import RxCocoa
import RxSwift
final class MainViewController: UIViewController {
#IBOutlet var addButton: UIButton!
#IBOutlet var tableView: UITableView!
let disposeBag = DisposeBag()
}
final class DetailViewController: UIViewController {
#IBOutlet var saveButton: UIButton!
#IBOutlet var nameField: UITextField!
let disposeBag = DisposeBag()
}
extension MainViewController {
func connect() {
let initial = Observable<[String]>.just([]) // This could be a network request
let addName = addButton.rx.tap
.flatMapFirst(presentScene(animated: true) {
DetailViewController().scene { $0.connect() }
})
let state = mainVieweModel(initial: initial, addName: addName)
.share(replay: 1)
state
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { _, name, cell in
cell.textLabel?.text = name
}
.disposed(by: disposeBag)
}
}
func mainVieweModel(initial: Observable<[String]>, addName: Observable<String>) -> Observable<[String]> {
enum Input {
case initial([String])
case add(String)
}
return Observable.merge(
initial.map { Input.initial($0) },
addName.map { Input.add($0) }
)
.scan(into: [String]()) { state, input in
switch input {
case let .initial(value):
state = value
case let .add(text):
state.append(text)
}
}
}
extension DetailViewController {
func connect() -> Observable<String> {
return saveButton.rx.tap
.withLatestFrom(nameField.rx.text.orEmpty)
.take(1)
}
}
The app delegate looks like this:
import Cause_Logic_Effect
import UIKit
#main
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = {
let result = UIWindow(frame: UIScreen.main.bounds)
result.rootViewController = MainViewController().configure { $0.connect() }
result.makeKeyAndVisible()
return result
}()
return true
}
}
So here is the problem that I have been going crazy with. I have an app that uses Realm as its Database. I have used Realm in the past with tableviews and it works properly. I can't seem to get the textField data that I saved to load into my view on viewDidLoad. With tableViews there is a reloadData method, but that isn't the case with textFields. I need the data that is in my data base to load into the view on viewDidLoad and I have confirmed several times that data has been saved and is sitting in the dataBase just waiting to load into the view, but it will not load.
import Cocoa
import RealmSwift
class PublisherViewController: NSViewController {
#IBOutlet weak var publisherName: NSTextField!
let realm = try! Realm()
var pubData : Results<Pub>?
override func viewDidLoad() {
super.viewDidLoad()
// Here is where textField.stringValues should load into the viewDidLoad
let theData = Pub()
theData.pubName = publisherName.stringValue
print("print \(theData)")
}
func save(pubData: Pub) {
do {
try realm.write {
realm.add(pubData)
}
} catch {
print("there was an error saving pubData \(error)")
}
}
#IBAction func savePublisher(_ sender: NSButton) {
let publisherData = Pub()
publisherData.pubName = publisherName.stringValue
save(pubData: publisherData)
}
}
Here is my data model
import Foundation
import RealmSwift
class Pub: Object {
#objc dynamic var pubName : String = """
}
Thanks to Mrkrisher on Discord here is the answer on how to display the last saved textViews and textFields from Realm into your viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
publisherName.stringValue = (pubData?.last?.pubName)?? ""
}
I am trying to make an app that uses firebase for authentication and database. This is my first app using firebase and I am unable to save files to firebase database. I am not getting any error in the console when I run the app but it is not saving anything to firebase. I read the firebase docs and followed the instruction but I am unable to get it to work. Help would be appreciated. Here is my code
import UIKit
import Firebase
import FirebaseDatabase
class AddVC: UIViewController {
var refAttractions: DatabaseReference! //defining firebase database reference
#IBOutlet weak var addedlbl: UILabel!
#IBOutlet weak var descriptioninfo: UITextField!
#IBOutlet weak var categoryinfo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// accessing nodes of refAttractiions
refAttractions = Database.database().reference().child("Attractions")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func submitbtn(_ sender: Any) {
addAttractions()
}
func addAttractions(){
let key = refAttractions.childByAutoId().key //creating id for the attraction.
let attraction = ["id": key,
"category": categoryinfo.text! as String,
"description": descriptioninfo.text! as String ]
refAttractions.child(key).setValue(attraction)
}
#IBAction func backbtn(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
Also, I have changed the rules in my firebase database to true for both read and write. Any help would be appreciated.
I am trying to use Parse PFUser in a software for OSX desktop. When I try to use it PFUser.query() it gives a message: Failed to set (contentViewController) user defined inspected property on (NSWindow): The class PFUser must be registered with registerSubclass before using Parse.
It is happening without registering the class.
I tried it registering the class this way: PFUser.registerSubclass() but it still doesn't work.
I will use the default PFUser without adding any fields to it, so I don't need to create a custom class to be my PFUser.
I tried to use PFUser.enableAutomaticUser() without success
Code below:
AppDelegate.swift
import Cocoa
import Parse
import Bolts
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let APP_ID = "app_id"
let CLIENT_KEY = "client_key"
let SERVER = "https://parseserver.com/"
func applicationDidFinishLaunching(_ aNotification: Notification) {
PFUser.registerSubclass()
let configuracaoParse = ParseClientConfiguration {
$0.applicationId = self.APP_ID
$0.clientKey = self.CLIENT_KEY
$0.server = self.SERVER
}
Parse.initialize(with: configuracaoParse)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
ViewController.swift
import Cocoa
import Parse
class ViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var senhaSecureTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
contaUsuarios()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func entrarButtonClicked(_ sender: NSButton) {
}
func contaUsuarios() {
let query = PFUser.query()
query?.countObjectsInBackground(block: {
(count, error) -> Void in
let numeroUsers = Int(UInt32(count))
if numeroUsers > 0 {
}
print(numeroUsers)
})
}
}
Reading some content on the internet I discovered that in OSX the ViewController is launched before the AppDelegate finishes loading, so I initialized the Parse connection and subclassing in the ViewController's viewDidLoad instead of AppDelegate and it is working just fine.
i am new to swift and tried to implement Google Auth with GPPSignInDelegate. I get the sign in dialog but the delegate methods:
- didDisconnectWithError
- finishedWithAuth
are never called. Maybe I am doing something wrong. I tried to translate it so swift and it looks ok, but something is not working. Any suggestions? Thanks for your help in advance.
class LoginViewController: UIViewController, GPPSignInDelegate {
var kClientID = "XYZ"
#IBOutlet weak var loginButton: UIButton!
#IBOutlet var gppsloginButton: GPPSignInButton!
var signIn = GPPSignIn.sharedInstance()
override func viewDidLoad() {
super.viewDidLoad()
//var signIn = GPPSignIn.sharedInstance()
signIn.clientID = kClientID;
signIn.scopes = [kGTLAuthScopePlusLogin]
signIn.delegate = self
signIn.authenticate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func finishedWithAuth(auth: GTMOAuth2Authentication, error: NSError ) -> Void{
debugPrintln("TEST")
}
func didDisconnectWithError ( error: NSError) -> Void{
debugPrintln("TEST2")
}
I think you missed to add the GPPURLHandler from your app delegate's URL handler in your AppDelegate.swift .
This handler will properly handle the URL that your application receives at the end of the authentication process.
func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
return GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation:annotation)
}