//

//  UserModel.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 9..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class UserModel: NSObject {

    

    @objc var profileImageUrl: String?

    @objc var userName: String?


}






//

//  MainViewController.swift -> PeopleViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 7..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import SnapKit

import Firebase


class PeopleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    var array :  [UserModel] = []

    var tableview : UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()


        tableview = UITableView()

        tableview.delegate = self

        tableview.dataSource = self

        tableview.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        view.addSubview(tableview)

        tableview.snp.makeConstraints { (m) in

            m.top.equalTo(view).offset(20)

            m.bottom.left.right.equalTo(view)

        }

        

            Database.database().reference().child("users").observe(DataEventType.value, with: { (snapshot) in

                

            

                self.array.removeAll()

                

                for child in snapshot.children {

                    let fchild = child as! DataSnapshot

                    let userModel = UserModel()

                    

                    userModel.setValuesForKeys(fchild.value as! [String : Any])

                    self.array.append(userModel)

                    

                }

                

                DispatchQueue.main.async {

                    self.tableview.reloadData();

                }

                

        })

            

        

        

        // Do any additional setup after loading the view.

    }


    

    

    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return array.count

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        

        let cell = tableview.dequeueReusableCell(withIdentifier: "Cell", for :indexPath)

        

        let imageview = UIImageView()

        cell.addSubview(imageview)

        imageview.snp.makeConstraints{(m) in

            m.centerY.equalTo(cell)

            m.left.equalTo(cell)

            m.height.width.equalTo(50)

        }

        

        URLSession.shared.dataTask(with: URL(string: array[indexPath.row].profileImageUrl!)!) { (data, response, err) in

            

            DispatchQueue.main.async {

                imageview.image = UIImage(data: data!)

                imageview.layer.cornerRadius = imageview.frame.size.width/2

                imageview.clipsToBounds = true

            }

        }.resume()

        

        let label = UILabel()

        cell.addSubview(label)

        label.snp.makeConstraints{ (m) in

            m.centerY.equalTo(cell)

            m.left.equalTo(imageview.snp.right).offset(30)

        }

        

        label.text = array[indexPath.row].userName

        

        return cell

    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 50

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}













//

//  LoginViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 5..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Firebase


class LoginViewController: UIViewController {


    @IBOutlet var email: UITextField!

    @IBOutlet var password: UITextField!

    @IBOutlet var loginButton: UIButton!

    @IBOutlet var signup: UIButton!

    let remoteConfig = RemoteConfig.remoteConfig()

    var color : String!

    override func viewDidLoad() {

        super.viewDidLoad()

        

        try! Auth.auth().signOut()

        let statusBar = UIView()

        self.view.addSubview(statusBar)

        statusBar.snp.makeConstraints {(m) in

            m.right.top.left.equalTo(self.view)

            m.height.equalTo(20)

            

        }

        color = remoteConfig["splash_background"].stringValue

        

        statusBar.backgroundColor = UIColor(hex: color)

        loginButton.backgroundColor = UIColor(hex: color)

        signup.backgroundColor = UIColor(hex: color)

        

        loginButton.addTarget(self, action: #selector(logingEvent), for: .touchUpInside)

        

        Auth.auth().addStateDidChangeListener{(auth, user) in

            if(user != nil){

                let view = self.storyboard?.instantiateViewController(withIdentifier: "MainViewTabBarController") as! UITabBarController

                self.present(view, animated: true, completion: nil)

            }

        }

        

        signup.addTarget(self, action: #selector(presentsSignup), for: .touchUpInside)

        // Do any additional setup after loading the view.

    }

    

    @objc func logingEvent(){

        Auth.auth().signIn(withEmail: email.text!, password: password.text!) {( user, err) in

            if(err != nil) {

                let alert = UIAlertController(title: "에러", message: err.debugDescription, preferredStyle: UIAlertControllerStyle.alert)

                alert.addAction(UIAlertAction(title: "확인",style: UIAlertActionStyle.default, handler: nil))

                self.present(alert, animated: true, completion: nil)

            }

        }

    }

    

    @objc func presentsSignup(){

        let view = self.storyboard?.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController

        self.present(view, animated: true, completion: nil)

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}









//

//  LoginViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 5..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Firebase


class LoginViewController: UIViewController {


    @IBOutlet var email: UITextField!

    @IBOutlet var password: UITextField!

    @IBOutlet var loginButton: UIButton!

    @IBOutlet var signup: UIButton!

    let remoteConfig = RemoteConfig.remoteConfig()

    var color : String!

    override func viewDidLoad() {

        super.viewDidLoad()

        

        try! Auth.auth().signOut()

        let statusBar = UIView()

        self.view.addSubview(statusBar)

        statusBar.snp.makeConstraints {(m) in

            m.right.top.left.equalTo(self.view)

            m.height.equalTo(20)

            

        }

        color = remoteConfig["splash_background"].stringValue

        

        statusBar.backgroundColor = UIColor(hex: color)

        loginButton.backgroundColor = UIColor(hex: color)

        signup.backgroundColor = UIColor(hex: color)

        

        loginButton.addTarget(self, action: #selector(logingEvent), for: .touchUpInside)

        

        Auth.auth().addStateDidChangeListener{(auth, user) in

            if(user != nil){

                let view = self.storyboard?.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController

                self.present(view, animated: true, completion: nil)

            }

        }

        

        signup.addTarget(self, action: #selector(presentsSignup), for: .touchUpInside)

        // Do any additional setup after loading the view.

    }

    

    @objc func logingEvent(){

        Auth.auth().signIn(withEmail: email.text!, password: password.text!) {( user, err) in

            if(err != nil) {

                let alert = UIAlertController(title: "에러", message: err.debugDescription, preferredStyle: UIAlertControllerStyle.alert)

                alert.addAction(UIAlertAction(title: "확인",style: UIAlertActionStyle.default, handler: nil))

                self.present(alert, animated: true, completion: nil)

            }

        }

    }

    

    @objc func presentsSignup(){

        let view = self.storyboard?.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController

        self.present(view, animated: true, completion: nil)

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}





//

//  SignupViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 5..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Firebase


class SignupViewController: UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate {

    

    @IBOutlet var imageView: UIImageView!

    

    @IBOutlet var email: UITextField!

    @IBOutlet var name: UITextField!

    

    @IBOutlet var password: UITextField!

   

    @IBOutlet var signup: UIButton!

    @IBOutlet var cancel: UIButton!

    

    let remoteConfig = RemoteConfig.remoteConfig()

    var color: String?


    override func viewDidLoad() {

        super.viewDidLoad()


        let statusBar = UIView()

        self.view.addSubview(statusBar)

        statusBar.snp.makeConstraints {(m) in

            m.right.top.left.equalTo(self.view)

            m.height.equalTo(20)

        }

        color = remoteConfig["splash_background"].stringValue

        

        statusBar.backgroundColor = UIColor(hex: color!)

        

        

        imageView.isUserInteractionEnabled = true

        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imagePicker)))

        

        

        signup.backgroundColor = UIColor(hex: color!)

        cancel.backgroundColor = UIColor(hex: color!)

        

        signup.addTarget(self, action: #selector(signupEvent), for: .touchUpInside)

        cancel.addTarget(self, action: #selector(cancelevent), for: .touchUpInside)

        // Do any additional setup after loading the view.

    }

    @objc func imagePicker(){

        

        let imagePicker = UIImagePickerController()

        imagePicker.delegate = self

        imagePicker.allowsEditing = true

        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary

        

        self.present(imagePicker, animated: true, completion: nil)

    }

    

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){

        imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

        

        dismiss(animated: true, completion: nil)

    }

    

    @objc func signupEvent(){

        Auth.auth().createUser(withEmail: email.text!, password: password.text!) {(user, err) in

            let uid = user?.uid

            

            let image = UIImageJPEGRepresentation(self.imageView.image!, 0.1)

            

            Storage.storage().reference().child("userImages").child(uid!).putData(image!, metadata: nil, completion: { (data, error) in

             

                let imageUrl = data?.downloadURL()?.absoluteString

                Database.database().reference().child("users").child(uid!).setValue(["userName":self.name.text!,"profileImageUrl":imageUrl])

            })

        }

    }

    

    @objc func cancelevent(){

        self.dismiss(animated: true, completion: nil)

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}













//

//  ViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 8. 30..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//



import UIKit

import SnapKit

import Firebase


class ViewController: UIViewController {


    var box = UIImageView() 

    var remoteConfig: RemoteConfig!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        remoteConfig = RemoteConfig.remoteConfig()

        let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true)

        remoteConfig.configSettings = remoteConfigSettings!

        remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")


        remoteConfig.fetch(withExpirationDuration: TimeInterval(0)) { (status, error) -> Void in

            if status == .success {

                print("Config fetched!")

                self.remoteConfig.activateFetched()

            } else {

                print("Config not fetched")

                print("Error: \(error!.localizedDescription)")

            }

            self.displayWelcome()

        }

        

        

        self.view.addSubview(box)

        box.snp.makeConstraints{(make) in

            make.center.equalTo(self.view)

        }

        box.image =  imageLiteral(resourceName: "loading_icon")

        self.view.backgroundColor = UIColor(hex: "#000000")

    }


    func displayWelcome(){

        let color = remoteConfig["splash_background"].stringValue

        let caps = remoteConfig["splash_message_caps"].boolValue

        let message = remoteConfig["splash_message"].stringValue

        

        if(caps){

            let alert = UIAlertController(title: "공지사항", message: message, preferredStyle: UIAlertControllerStyle.alert)

            alert.addAction(UIAlertAction(title: "확인", style: UIAlertActionStyle.default, handler: { (action) in

                exit(0)

            }))

            self.present(alert, animated: true, completion: nil)

        }else{

            let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController



            self.present(loginVC, animated: false, completion: nil)

        }

        self.view.backgroundColor = UIColor(hex: color!)

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}


extension UIColor {

    convenience init(hex: String) {

        let scanner = Scanner(string: hex)

        

        scanner.scanLocation = 1

        

        var rgbValue: UInt64 = 0

        

        scanner.scanHexInt64(&rgbValue)

        

        let r = (rgbValue & 0xff0000) >> 16

        let g = (rgbValue & 0xff00) >> 8

        let b = rgbValue & 0xff

        

        self.init(

            red: CGFloat(r) / 0xff,

            green: CGFloat(g) / 0xff,

            blue: CGFloat(b) / 0xff, alpha: 1

        )

    }

}





//

//  LoginViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 5..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Firebase


class LoginViewController: UIViewController {


    @IBOutlet var loginButton: UIButton!

    @IBOutlet var signup: UIButton!

    let remoteConfig = RemoteConfig.remoteConfig()

    var color : String!

    override func viewDidLoad() {

        super.viewDidLoad()

        

        let statusBar = UIView()

        self.view.addSubview(statusBar)

        statusBar.snp.makeConstraints {(m) in

            m.right.top.left.equalTo(self.view)

            m.height.equalTo(20)

            

        }

        color = remoteConfig["splash_background"].stringValue

        

        statusBar.backgroundColor = UIColor(hex: color)

        loginButton.backgroundColor = UIColor(hex: color)

        signup.backgroundColor = UIColor(hex: color)

        

        signup.addTarget(self, action: #selector(presentsSignup), for: .touchUpInside)

        // Do any additional setup after loading the view.

    }

    

    @objc func presentsSignup(){

        let view = self.storyboard?.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController

        self.present(view, animated: true, completion: nil)

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}





//

//  SignupViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 5..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Firebase


class SignupViewController: UIViewController {

    

    

    @IBOutlet var email: UITextField!

    @IBOutlet var name: UITextField!

    

    @IBOutlet var password: UITextField!

   

    @IBOutlet var signup: UIButton!

    @IBOutlet var cancel: UIButton!

    

    let remoteConfig = RemoteConfig.remoteConfig()

    var color: String?


    override func viewDidLoad() {

        super.viewDidLoad()


        let statusBar = UIView()

        self.view.addSubview(statusBar)

        statusBar.snp.makeConstraints {(m) in

            m.right.top.left.equalTo(self.view)

            m.height.equalTo(20)

        }

        color = remoteConfig["splash_background"].stringValue

        

        statusBar.backgroundColor = UIColor(hex: color!)

        signup.backgroundColor = UIColor(hex: color!)

        cancel.backgroundColor = UIColor(hex: color!)

        

        signup.addTarget(self, action: #selector(signupEvent), for: .touchUpInside)

        cancel.addTarget(self, action: #selector(cancelevent), for: .touchUpInside)

        // Do any additional setup after loading the view.

    }

    

    @objc func signupEvent(){

        Auth.auth().createUser(withEmail: email.text!, password: password.text!) {(user, err) in

            let uid = user?.uid

            Database.database().reference().child("users").child(uid!).setValue(["name":self.name.text!])

        }

    }

    @objc func cancelevent(){

        self.dismiss(animated: true, completion: nil)

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}





















//

//  ViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 8. 30..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//



import UIKit

import SnapKit

import Firebase


class ViewController: UIViewController {


    var box = UIImageView() 

    var remoteConfig: RemoteConfig!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        remoteConfig = RemoteConfig.remoteConfig()

        let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true)

        remoteConfig.configSettings = remoteConfigSettings!

        remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")


        remoteConfig.fetch(withExpirationDuration: TimeInterval(0)) { (status, error) -> Void in

            if status == .success {

                print("Config fetched!")

                self.remoteConfig.activateFetched()

            } else {

                print("Config not fetched")

                print("Error: \(error!.localizedDescription)")

            }

            self.displayWelcome()

        }

        

        

        self.view.addSubview(box)

        box.snp.makeConstraints{(make) in

            make.center.equalTo(self.view)

        }

        box.image =  imageLiteral(resourceName: "loading_icon")

        self.view.backgroundColor = UIColor(hex: "#000000")

    }


    func displayWelcome(){

        let color = remoteConfig["splash_background"].stringValue

        let caps = remoteConfig["splash_message_caps"].boolValue

        let message = remoteConfig["splash_message"].stringValue

        

        if(caps){

            let alert = UIAlertController(title: "공지사항", message: message, preferredStyle: UIAlertControllerStyle.alert)

            alert.addAction(UIAlertAction(title: "확인", style: UIAlertActionStyle.default, handler: { (action) in

                exit(0)

            }))

            self.present(alert, animated: true, completion: nil)

        }else{

            let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController



            self.present(loginVC, animated: false, completion: nil)

        }

        self.view.backgroundColor = UIColor(hex: color!)

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}


extension UIColor {

    convenience init(hex: String) {

        let scanner = Scanner(string: hex)

        

        scanner.scanLocation = 1

        

        var rgbValue: UInt64 = 0

        

        scanner.scanHexInt64(&rgbValue)

        

        let r = (rgbValue & 0xff0000) >> 16

        let g = (rgbValue & 0xff00) >> 8

        let b = rgbValue & 0xff

        

        self.init(

            red: CGFloat(r) / 0xff,

            green: CGFloat(g) / 0xff,

            blue: CGFloat(b) / 0xff, alpha: 1

        )

    }

}





//

//  LoginViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 5..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Firebase


class LoginViewController: UIViewController {


    @IBOutlet var loginButton: UIButton!

    @IBOutlet var signIn: UIButton!

    let remoteConfig = RemoteConfig.remoteConfig()

    var color : String!

    override func viewDidLoad() {

        super.viewDidLoad()

        let statusBar = UIView()

        self.view.addSubview(statusBar)

        statusBar.snp.makeConstraints {(m) in

            m.right.top.left.equalTo(self.view)

            m.height.equalTo(20)

            

        }

        color = remoteConfig["splash_background"].stringValue

        statusBar.backgroundColor = UIColor(hex: color)

        loginButton.backgroundColor = UIColor(hex: color)

        signIn.backgroundColor = UIColor(hex: color)

        

        

        // Do any additional setup after loading the view.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destinationViewController.

        // Pass the selected object to the new view controller.

    }

    */


}















//

//  ViewController.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 8. 30..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//



import UIKit

import SnapKit

import Firebase


class ViewController: UIViewController {


    var box = UIImageView()

    var remoteConfig: RemoteConfig!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        remoteConfig = RemoteConfig.remoteConfig()

        let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true)

        remoteConfig.configSettings = remoteConfigSettings!

        remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")


        remoteConfig.fetch(withExpirationDuration: TimeInterval(0)) { (status, error) -> Void in

            if status == .success {

                print("Config fetched!")

                self.remoteConfig.activateFetched()

            } else {

                print("Config not fetched")

                print("Error: \(error!.localizedDescription)")

            }

            self.displayWelcome()

        }

        

        

        self.view.addSubview(box)

        box.snp.makeConstraints{(make) in

            make.center.equalTo(self.view)

        }

        box.image =  imageLiteral(resourceName: "loading_icon")

        self.view.backgroundColor = UIColor(hex: "#000000")

    }


    func displayWelcome(){

        let color = remoteConfig["splash_background"].stringValue

        let caps = remoteConfig["splash_message_caps"].boolValue

        let message = remoteConfig["splash_message"].stringValue

        

        if(caps){

            let alert = UIAlertController(title: "공지사항", message: message, preferredStyle: UIAlertControllerStyle.alert)

            alert.addAction(UIAlertAction(title: "확인", style: UIAlertActionStyle.default, handler: { (action) in

                exit(0)

            }))

            self.present(alert, animated: true, completion: nil)

        }

        self.view.backgroundColor = UIColor(hex: color!)

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}


extension UIColor {

    convenience init(hex: String) {

        let scanner = Scanner(string: hex)

        

        scanner.scanLocation = 1

        

        var rgbValue: UInt64 = 0

        

        scanner.scanHexInt64(&rgbValue)

        

        let r = (rgbValue & 0xff0000) >> 16

        let g = (rgbValue & 0xff00) >> 8

        let b = rgbValue & 0xff

        

        self.init(

            red: CGFloat(r) / 0xff,

            green: CGFloat(g) / 0xff,

            blue: CGFloat(b) / 0xff, alpha: 1

        )

    }

}



파이어베이스 ios 구글 로그인 방식을 구현해 보았습니다.



최대한 파이어베이스 문서 위주로 구현하였습니다.


https://firebase.google.com/docs



프로젝트를 만듭니다.




파이어베이스 콘솔로 이동하여서 프로젝트를 추가합니다.


https://console.firebase.google.com/





프로젝트를 추가한 후에는 앱을 추가해줍니다.





앱을 추가할 때는    xcode  에서 bundle identifier 에서 입력된 값을 넣어주어야 합니다.


googleservice-info.plist 다운 받을 때는 뒤에 ( ) 괄호가 붙지 않게 원본 그대로 수정해주셔야 합니다.







아래와 같이 (1)을 삭제해서 원본 그대로 수정해줍니다.









finder에서  googleservice-info.plist 파일을 xcode 로 복사해줍니다.



cooapod 를 설치해주어야 합니다. 



Cocoa pods install


https://guides.cocoapods.org/using/getting-started.html#getting-started





설치한 후에는 xcode project 실제 위치에 가서 pod init  후에 Podfile 을 아래와 같이 수정해줍니다.







수정한 후에는 pod install 을 수행해줍니다.




위에 경고대로 현재 열려있는 xcode 를 닫은 후에 아래와 같이 workspace를 open 해주면 아래와 같은 창이 실행됩니다.







firebase console 로 이동한 후에 authentication 에서 로그인 방법에서 google 을 사용가능하도록 수정해줍니다.






appdelegate와 viewcontroller 파일에 import 해줍니다.




googleservice-info.plist 에서 reversed_client_id 복사한 후에 url_type에  붙여넣습니다.



firebase 문서를 참고하면서 아래 스크립트들을 입력해줍니다.





아래와 같이 뷰를 추가해줍니다. 




뷰를 추가해 준 후에 class에서 아래와 같이 입력해줍니다.




버튼을 아래와 같이 연결해줍니다.





fireabase 문서에서 권장해주는 크기로 수정해줍니다.





appdelegate  에서 credential 밑에 아래와 같이 추가해줍니다.



firebase console에서 authentication 사용자를 보면 아직 사용자가 없다고 나옵니다.




xcode 에서 시뮬리에션을 실행해봅니다.





아이디와 패스워드를 입력하면 아래와 같이 로그인에 성공한 것을 확인할 수 있습니다. 




고맙습니다.

+ Recent posts