{ "jokes" : { "e32e223r44" : { "jokeText" : "What did one computer say to the other? 11001001010101" } } }
import Foundation let BASE_URL = "https://jokes-matt-maher.firebaseio.com"
cd <your-xcode-project-directory> pod init
open -a Xcode Podfile
platform :ios, '8.0' use_frameworks! pod 'Firebase', '>= 2.5.0'
pod install
#import <Firebase/Firebase.h>
import Foundation import Firebase class DataService { static let dataService = DataService() private var _BASE_REF = Firebase(url: "\(BASE_URL)") private var _USER_REF = Firebase(url: "\(BASE_URL)/users") private var _JOKE_REF = Firebase(url: "\(BASE_URL)/jokes") var BASE_REF: Firebase { return _BASE_REF } var USER_REF: Firebase { return _USER_REF } var CURRENT_USER_REF: Firebase { let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String let currentUser = Firebase(url: "\(BASE_REF)").childByAppendingPath("users").childByAppendingPath(userID) return currentUser! } var JOKE_REF: Firebase { return _JOKE_REF } }
import UIKit import Firebase class CreateAccountViewController: UIViewController {
@IBAction func createAccount(sender: AnyObject) { let username = usernameField.text let email = emailField.text let password = passwordField.text if username != "" && email != "" && password != "" { // Set Email and Password for the New User. DataService.dataService.BASE_REF.createUser(email, password: password, withValueCompletionBlock: { error, result in if error != nil { // There was a problem. self.signupErrorAlert("Oops!", message: "Having some trouble creating your account. Try again.") } else { // Create and Login the New User with authUser DataService.dataService.BASE_REF.authUser(email, password: password, withCompletionBlock: { err, authData in let user = ["provider": authData.provider!, "email": email!, "username": username!] // Seal the deal in DataService.swift. DataService.dataService.createNewAccount(authData.uid, user: user) }) // Store the uid for future access - handy! NSUserDefaults.standardUserDefaults().setValue(result ["uid"], forKey: "uid") // Enter the app. self.performSegueWithIdentifier("NewUserLoggedIn", sender: nil) } }) } else { signupErrorAlert("Oops!", message: "Don't forget to enter your email, password, and a username.") } }
func signupErrorAlert(title: String, message: String) { // Called upon signup error to let the user know signup didn't work. let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(action) presentViewController(alert, animated: true, completion: nil) }
func createNewAccount(uid: String, user: Dictionary<String, String>) { // A User is born. USER_REF.childByAppendingPath(uid).setValue(user) }
override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // If we have the uid stored, the user is already logger in - no need to sign in again! if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil && DataService.dataService.CURRENT_USER_REF.authData != nil { self.performSegueWithIdentifier("CurrentlyLoggedIn", sender: nil) } }
@IBAction func tryLogin(sender: AnyObject) { let email = emailField.text let password = passwordField.text if email != "" && password != "" { // Login with the Firebase's authUser method DataService.dataService.BASE_REF.authUser(email, password: password, withCompletionBlock: { error, authData in if error != nil { print(error) self.loginErrorAlert("Oops!", message: "Check your username and password.") } else { // Be sure the correct uid is stored. NSUserDefaults.standardUserDefaults().setValue(authData.uid, forKey: "uid") // Enter the app! self.performSegueWithIdentifier("CurrentlyLoggedIn", sender: nil) } }) } else { // There was a problem loginErrorAlert("Oops!", message: "Don't forget to enter your email and password.") } } func loginErrorAlert(title: String, message: String) { // Called upon login error to let the user know login didn't work. let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(action) presentViewController(alert, animated: true, completion: nil) }
class Joke { private var _jokeRef: Firebase! private var _jokeKey: String! private var _jokeText: String! private var _jokeVotes: Int! private var _username: String! var jokeKey: String { return _jokeKey } var jokeText: String { return _jokeText } var jokeVotes: Int { return _jokeVotes } var username: String { return _username } // Initialize the new Joke init(key: String, dictionary: Dictionary<String, AnyObject>) { self._jokeKey = key // Within the Joke, or Key, the following properties are children if let votes = dictionary["votes"] as? Int { self._jokeVotes = votes } if let joke = dictionary["jokeText"] as? String { self._jokeText = joke } if let user = dictionary["author"] as? String { self._username = user } else { self._username = "" } // The above properties are assigned to their key. self._jokeRef = DataService.dataService.JOKE_REF.childByAppendingPath(self._jokeKey) } }
override func viewDidLoad() { super.viewDidLoad() // Get username of the current user, and set it to currentUsername, so we can add it to the Joke. DataService.dataService.CURRENT_USER_REF.observeEventType(FEventType.Value, withBlock: { snapshot in let currentUser = snapshot.value.objectForKey("username") as! String print("Username: \(currentUser)") self.currentUsername = currentUser }, withCancelBlock: { error in print(error.description) }) }
var currentUsername = ""
@IBAction func saveJoke(sender: AnyObject) { let jokeText = jokeField.text if jokeText != "" { // Build the new Joke. // AnyObject is needed because of the votes of type Int. let newJoke: Dictionary<String, AnyObject> = [ "jokeText": jokeText!, "votes": 0, "author": currentUsername ] // Send it over to DataService to seal the deal. DataService.dataService.createNewJoke(newJoke) if let navController = self.navigationController { navController.popViewControllerAnimated(true) } } }
func createNewJoke(joke: Dictionary<String, AnyObject>) { // Save the Joke // JOKE_REF is the parent of the new Joke: "jokes". // childByAutoId() saves the joke and gives it its own ID. let firebaseNewJoke = JOKE_REF.childByAutoId() // setValue() saves to Firebase. firebaseNewJoke.setValue(joke) }
@IBAction func logout(sender: AnyObject) { // unauth() is the logout method for the current user. DataService.dataService.CURRENT_USER_REF.unauth() // Remove the user's uid from storage. NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "uid") // Head back to Login! let loginViewController = self.storyboard!.instantiateViewControllerWithIdentifier("Login") UIApplication.sharedApplication().keyWindow?.rootViewController = loginViewController }
var jokes = [Joke]() override func viewDidLoad() { super.viewDidLoad() // observeEventType is called whenever anything changes in the Firebase - new Jokes or Votes. // It's also called here in viewDidLoad(). // It's always listening. DataService.dataService.JOKE_REF.observeEventType(.Value, withBlock: { snapshot in // The snapshot is a current look at our jokes data. print(snapshot.value) self.jokes = [] if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] { for snap in snapshots { // Make our jokes array for the tableView. if let postDictionary = snap.value as? Dictionary<String, AnyObject> { let key = snap.key let joke = Joke(key: key, dictionary: postDictionary) // Items are returned chronologically, but it's more fun with the newest jokes first. self.jokes.insert(joke, atIndex: 0) } } } // Be sure that the tableView updates when there is new data. self.tableView.reloadData() }) }
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return jokes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let joke = jokes[indexPath.row] // We are using a custom cell. if let cell = tableView.dequeueReusableCellWithIdentifier("JokeCellTableViewCell") as? JokeCellTableViewCell { // Send the single joke to configureCell() in JokeCellTableViewCell. cell.configureCell(joke) return cell } else { return JokeCellTableViewCell() } } configureCell(), in JokeCellTableViewCell.swift, is where we set the labels and listen for a vote tap. func configureCell(joke: Joke) { self.joke = joke // Set the labels and textView. self.jokeText.text = joke.jokeText self.totalVotesLabel.text = "Total Votes: \(joke.jokeVotes)" self.usernameLabel.text = joke.username // Set "votes" as a child of the current user in Firebase and save the joke's key in votes as a boolean. voteRef = DataService.dataService.CURRENT_USER_REF.childByAppendingPath("votes").childByAppendingPath(joke.jokeKey) // observeSingleEventOfType() listens for the thumb to be tapped, by any user, on any device. voteRef.observeSingleEventOfType(.Value, withBlock: { snapshot in // Set the thumb image. if let thumbsUpDown = snapshot.value as? NSNull { // Current user hasn't voted for the joke... yet. print(thumbsUpDown) self.thumbVoteImage.image = UIImage(named: "thumb-down") } else { // Current user voted for the joke! self.thumbVoteImage.image = UIImage(named: "thumb-up") } }) } func configureCell(joke: Joke) { self.joke = joke // Set the labels and textView. self.jokeText.text = joke.jokeText self.totalVotesLabel.text = "Total Votes: \(joke.jokeVotes)" self.usernameLabel.text = joke.username // Set "votes" as a child of the current user in Firebase and save the joke's key in votes as a boolean. voteRef = DataService.dataService.CURRENT_USER_REF.childByAppendingPath("votes").childByAppendingPath(joke.jokeKey) // observeSingleEventOfType() listens for the thumb to be tapped, by any user, on any device. voteRef.observeSingleEventOfType(.Value, withBlock: { snapshot in // Set the thumb image. if let thumbsUpDown = snapshot.value as? NSNull { // Current user hasn't voted for the joke... yet. print(thumbsUpDown) self.thumbVoteImage.image = UIImage(named: "thumb-down") } else { // Current user voted for the joke! self.thumbVoteImage.image = UIImage(named: "thumb-up") } }) }
var joke: Joke! var voteRef: Firebase! override func awakeFromNib() { super.awakeFromNib() // UITapGestureRecognizer is set programatically. let tap = UITapGestureRecognizer(target: self, action: "voteTapped:") tap.numberOfTapsRequired = 1 thumbVoteImage.addGestureRecognizer(tap) thumbVoteImage.userInteractionEnabled = true }
func voteTapped(sender: UITapGestureRecognizer) { // observeSingleEventOfType listens for a tap by the current user. voteRef.observeSingleEventOfType(.Value, withBlock: { snapshot in if let thumbsUpDown = snapshot.value as? NSNull { print(thumbsUpDown) self.thumbVoteImage.image = UIImage(named: "thumb-down") // addSubtractVote(), in Joke.swift, handles the vote. self.joke.addSubtractVote(true) // setValue saves the vote as true for the current user. // voteRef is a reference to the user's "votes" path. self.voteRef.setValue(true) } else { self.thumbVoteImage.image = UIImage(named: "thumb-up") self.joke.addSubtractVote(false) self.voteRef.removeValue() } }) }
// Add or Subtract a Vote from the Joke. func addSubtractVote(addVote: Bool) { if addVote { _jokeVotes = _jokeVotes + 1 } else { _jokeVotes = _jokeVotes - 1 } // Save the new vote total. _jokeRef.childByAppendingPath("votes").setValue(_jokeVotes) }
Source: https://habr.com/ru/post/277941/
All Articles