Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // FirebaseConnection.swift
- // VoxWebMusic
- //
- // Created by Danilo Mozer on 27/11/17.
- // Copyright © 2017 Diet Code Apps. All rights reserved.
- //
- import Foundation
- import Firebase
- import FirebaseAuth
- import FirebaseStorage
- import FirebaseDatabase
- struct FirebaseConnection{
- var databaseRef : DatabaseReference{
- return Database.database().reference()
- }
- var storageRef : StorageReference{
- return Storage.storage().reference()
- }
- // 1 --- We Create the User
- func signUp(email: String, firstName: String, lastName: String, password: String, data: NSData!){
- Auth.auth().createUser(withEmail: email, password: password, completion:{ (user, error) in
- if error == nil {
- self.setUserInfo(user: user!, firstName: firstName, lastName: lastName, password: password, data: data)
- }else{
- print(error!.localizedDescription)
- }
- })
- }
- // 2 --- Set user Info
- private func setUserInfo(user: User, firstName: String, lastName: String, password: String, data: NSData){
- //Create Path for the user image
- let imagePath = "profile\(user.uid)/userPic.jpg"
- //Create image reference
- let imageRef = storageRef.child(imagePath)
- //Create metadata for the image
- let metaData = StorageMetadata()
- //Save the user image in the Firebase Storage File
- imageRef.putData(data as Data, metadata: metaData) { (data, error) in
- if error == nil{
- let changeRequest = user.createProfileChangeRequest()
- changeRequest.displayName = ("\(firstName) \(lastName)")
- changeRequest.photoURL = metaData.downloadURL()
- changeRequest.commitChanges(completion: { (error) in
- if error == nil {
- self.saveInfo(user: user, firstName: firstName, lastName: lastName, password: password)
- }
- })
- }else{
- print(error!.localizedDescription)
- }
- }
- }
- // 3 --- Saving user info
- private func saveInfo(user: User, firstName: String, lastName: String, password: String){
- // Create user dictionary info
- let userInfo = ["email": user.email!,"firstName": firstName,"lastName": lastName,"photoURL": (user.photoURL!)] as [String : Any]
- //Create reference
- let userRef = databaseRef.child("users").child(user.uid)
- //Save the user info in the Database
- userRef.setValue(userInfo)
- signIn(email: user.email!, password: password)
- }
- //4 --- Signing In
- func signIn(email: String, password: String){
- Auth.auth().signIn(withEmail: email, password: password, completion: { (user,error) in
- if error == nil{
- if let user = user {
- print ("\(user.displayName!) has signed in sucessfully!")
- }
- }else{
- print(error!.localizedDescription)
- }
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement