قالب وردپرس درنا توس
Home / IOS Development / Firebase Tutorial | Cocoanetics

Firebase Tutorial | Cocoanetics



Since the official Parse shutdown, many people are looking for alternatives. Google established Firebase as one such option for your web-based backend. In deze tutorial zullen we exploreren hoe te bouwen een iOS-app die gebruik maakt van Google Firebase als backend.

My name is Bernhard Götzendorfer and I'm currently interning at Cocoanetics. I've spent some time working with Google's Firebase and since I wanted to start blogging, I will take this opportunity and walk you through the steps to create a simple iOS App using Firebase.

Then click Add App ]. This will generate a GoogleService-Info.plist which downloads.

  • Open your Terminal, navigate to the project location. One quick way to do that is to enter cd and then drag the project folder onto the terminal window.
  • Create a new Podfile by typing pod init .

There are

  • Move the cursor to Press Press Press Press Press Press Press to activate insert mode and type Pod Firebase / Database
  • ESC to leave insert mode.
  • To Exit type : wq to Write and Quit.

  • Type in your Terminal "pod install" to install the pod and generate a workspace for Xcode.
  • Note: You need to close your Xcode project and instead open the newly generated xcworkspace
    In other words, you will not be able to compile because only the work space has the necessary pod references.

    Firebase Code Setup

    In AppDelegate.swift we add an import for the Firebase module and call to the configure function within didFinishLaunchingWithOptions as shown below.

    Firebase Authentication Rules

    As the last step for configuring Firebase, we need to modify the authentication rules in the Firebase console. If you still see the Add Firebase to my iOS App popup, then close that by clicking on the X.

    Click on the Database tab on the left side and click on Rules at the top. Modify the rules to look like shown in the screenshot below:

    For this tutorial we will not need any more elaborate authentication, so we just make read access public. For more information about this refer to https://firebase.google.com/docs/database/security/quickstart.

    Firebase setup is now complete!

    Building the Messaging App

    With Firebase setup now complete,

  • Delete ViewController.swift – Move to Trash.
  • We can continue with creating our tutorial app.

    Right-click on the FirebaseDemo folder in project navigator and select New File .

  • Create a Cocoa Touch Class – Subclass of UIViewController named AddViewController .

  • Repeat that step but with Subclass or UITableViewController named MessageTableViewController .

  • And our last one: Choose Swift File and name it Message .

  • Xcode will add .swift to all these new files. Your file structure should look like this:

    Go to your Main.storyboard and delete your current view controller.

    • Search for Table View Controller in the object browser (bottom right of the inspector panel) and drag it into your storyboard.

      • Select the new Table View Controller and in the Menu Bar at the top select Editor -> Embed -> Navigation Controller. This creates a new navigation controller that has the table view controller as root.

      • In the attribute inspector for the new navigation controller, check "Is Initial View Controller" – this is our App's starting point.

      • Search for a Bar Button Item on the bottom right and insert it at the top right of the navigation bar on the table view controller. Change the System Item to Add.

      • Drag a new View Controller onto the canvas.

      • Control + drag the plus button to the view controller and select the Show option in the popup.

        If you now click on the + in your app, it will navigate you to the view controller.

      Label

    • Label
    • Label
    • Button View
    • Button

    Make

    Label

    Make

    Add to Cart Sikkert at du tilføjer dem alle ind i Stack View! The view controller should look like this:

    Now we need outlets for the text field and picker and an action for the Send button. Show the assistant inspector via the button with the two circles and control + drag from the elements onto the code pane. For the text field, select an outlet. For the picker as well. For the button, change the Connection Type to Action. I named them messageField recipientPicker and sendMessage .

    For simplicity the data source for the recipient picker will be merely a static array of names.

    ]

    We make the view controller the delegate and data source for the picker view.


    You can find the code for my sample project on GitHub. I will not reproduce all the code in the project in this blog post, only two parts as they show how to talk to Firebase from Swift.

    Communicating with Firebase requires a bit of unusual syntax, but it is very simple. This is how a new message was sent in. AddViewController.swift :

     func msg (to user: String, withText msg: String)
    {
       // Build the Connection to the Firebase Database
       light firebaseRef = FIRDatabase.database (). reference ()
            
       // Tell Firebase the structure
       let msgDict = ["recipient": user, "msg": msg]
            
       // Tell Firebase where to save and save the Value
       firebaseRef.child ( "Messages"). childByAutoId (). SetValue (msgDict)
    }
    

    This gets a reference to the database and then tells it to add a new child object with an automatic identifier. De noodzakelijke velden worden ingeleid uit de woordenboek. This is quite similar to Parse.

    To have the message table view be automatically updated by firebase can tell it to send us notifications whenever something changes.

     func observeMessages (withHandler trades: @escaping (_ Message: Message) -> ()) The following function launches an observation where every time a new object is added.
    {
       FIRDatabase.database (). Reference (). Childrens ( "Messages"). QueryOrderedByKey ().
          observe (.childAdded, with: {(snapshot)
                    
             let dict = snapshot.value as! NSDictionary
                    
             guard let to = dict ["recipient"] as? String,
                   let msg = dict ["msg"] as? String else
             {
                print ("error in msg")
                return
             }
                    
             let msgObj = Message (two: two, msg: msg)
                    
             Trades (msgObj)
          })
    }
    

    The establishes an ongoing query for the Messages entity. In the table view's viewDidLoad we give it a handler to be called for each new message.

     override func viewDidLoad ()
    {
       super.viewDidLoad ()
    
       // Needed to load the Data with ObserverMessages and put it into our Array.
       // messages and later into the TableViewController
       observeMessages {(message)
                    
          self.messages.insert (message, at: 0)
          self.tableView.reloadData ()
       }
    }
    

    I encourage you to try to understand the contents of Message.swift MessageTableViewController and AddViewController and how they interact with each other.

    Conclusion

    I had great fun creating this tutorial and trying it out with several of my friends. I found that when you are explaining a concept that is new to yourself, it helps to put yourself into the frame of mind or somebody who needs to explain it to somebody else.

    Google Firebase is still a mystery to me , men det ser ut som om jeg gjorde de første suksessfulle trinnene med sine krefter for mine egne applikasjoner. Men, den største fordelen for meg personlig var at jeg fikk mye bedre å lage grunnleggende om en ny iOS-app, som å sette opp Xcode, legge til CocoaPods, modifying the storyboard i Interface Builder og meget mere.

    I welcome your feedback. Du kan enten sende meg en mail eller skapa et problem på GitHub. Special thanks to Oliver for motivating and mentoring me, my teachers for giving me a good start to programming and all the people who follow the same path as I do and are part of my life.


    Source link