1. 프로젝트 추가하기

 

2. 프로젝트 설정하기

iOS 번들 ID에는 Xcode의 프로젝트 이름과 일치하게 만든다.

App Store ID는 개발자 계정의 ID를 넣으면 된다.

 

'구성 파일 다운로드'에서 plist 파일을 받아 Xcode 프로젝트에 넣는다. 위치는 위 그림대로 넣는다.

 

시키는대로 CocoaPods Docs 페이지로 이동해서 CocoaPods를 설치하고 init을 진행한다.

sudo gem install cocoapods
pod init

 

터미널로 현재 프로젝트 파일이 있는 위치로 이동한 다음 vi 에디터로 Podfile을 열어

pod 'Firebase/Analytics'

를 마지막 end 앞에 넣어준다.

(지금부터 스샷은 프로젝트 명이 test가 아니고 smartFinance다. smartFinance가 이미 있어서 test로 찍었음...)

 

이제 Xcode를 닫고 터미널에 다음을 명령한다.

pod install

 

지금부터는 기존 Xcode 프로젝트 파일 말고 Xcode를 새로 생긴 하얀색 파일로 실행할거다. 클릭해서 Xcode 프로젝트를 열자.

 

시키는대로 추가하고 저장한다.

 

5번 단계에서 Firebase 서버가 앱 실행을 확인한다. 이 때 Xcode에서 Build를 Run 시켜서 연결이 확인되면 등록이 완료된다.

 

3. Main.storyboard에 로그인 폼 만들기

Labe, Text Field, Button을 만들고 변수, 함수로 할당한다. 비밀번호가 입력되는 Text Field는 우측 속성 창에서 'Secure Text Entry'를 체크해서 입력되는 문자가 보이지 않게 한다.

 

4. Firebase 인증 연결하기

 

 

Xcode 프로젝트를 다시 종료한 다음 진행한다. 시키는대로 터미널에서 프로젝트 폴더로 이동해 Podfile을 vi 에디터로 열고 Auth를 추가한 후 pod install을 명령한다. 그러면 추가로 필요한 모듈들을 가져와 설치한다. 그리고 Xcode 프로젝트를 재시작한다.(Xcode 종료 후 하얀색 프로젝트 파일로 열기)

이 부분은 위에서 처음 Firebase 프로젝트 생성할 때 한 부분으로 건너뛴다.

 

4.1 신규 사용자 가입

//
//  ViewController.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var m_id: UITextField!
    @IBOutlet weak var m_pwd: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func tapLogin(_ sender: Any) {
    }
    @IBAction func tapSignUp(_ sender: Any) {
    }
//    m_id.text
//    m_pwd.text
    
    
}

tapSignUp에 넣을거다.

//
//  ViewController.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var m_id: UITextField!
    @IBOutlet weak var m_pwd: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func tapLogin(_ sender: Any) {
    }
    @IBAction func tapSignUp(_ sender: Any) {
        Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
          // ...
        }EmailViewController.swift
    }
//    m_id.text
//    m_pwd.text
    
    
}

 

'email'과 'password' 변수를 모르겠다고 빨간색 에러가 뜰거다. 우리 프로젝트에 맞게 바꿔준다. 그리고 구글 Firebase docs에는 나와있지 않지만 'EmailViewController.swift'를 누르고 들어가보면 ViewController 여기도 Fireabase를 추가해준다.

 

결과를 확인하기 위해 print를 추가하고 break point를 잡아준다.

//
//  ViewController.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit
import Firebase

class ViewController: UIViewController {

    @IBOutlet weak var m_id: UITextField!
    @IBOutlet weak var m_pwd: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func tapLogin(_ sender: Any) {
    }
    @IBAction func tapSignUp(_ sender: Any) {
//            m_id.text
//            m_pwd.text
        Auth.auth().createUser(withEmail: m_id.text!, password: m_pwd.text!) { authResult, error in
          // ...
            print(authResult)
        }
    }
}

 

이제 빌드를 한 다음 'abc@abc.com', 'test1234'를 넣고 SignUp을 누른다.

 

이제 Firebase로 돌아가 새로고침을 하면 사용자가 추가되어있다.

 

4.2 사용자 로그인

위에 사용자 가입 할때와 마찬가지로 로그인 function 버튼에 추가하고 변수 명을 우리 프로젝트에 맞게 바꿔준다.

//
//  ViewController.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit
import Firebase

class ViewController: UIViewController {

    @IBOutlet weak var m_id: UITextField!
    @IBOutlet weak var m_pwd: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func tapLogin(_ sender: Any) {
        Auth.auth().signIn(withEmail: m_id.text!, password: m_pwd.text!) { [weak self] authResult, error in
          guard let strongSelf = self else { return }
          // ...
            print(strongSelf)
        }
    }
    @IBAction func tapSignUp(_ sender: Any) {
//            m_id.text
//            m_pwd.text
        Auth.auth().createUser(withEmail: m_id.text!, password: m_pwd.text!) { authResult, error in
          // ...
            print(authResult)
        }
    }
}

 

이제 위에서 가입할 때 사용한 'abc@abc.com'과 'test1234'를 넣고 로그인을 해본다. 현재 다른 기능을 구현하지 않아 로그인이 성공해도 다른 반응은 없겠지만 error가 nill(없음)이 나온다면 로그인이 성공한 것이다.

 

매번 아이디 비밀번호 입력하기 귀찮으니 테스트용으로 값을 아예 넣어두자.

 

동일한 아이디로 가입을 다시 눌러보면 에러가 발생한다.

 

 

 

 

AppDelegate.swift

//
//  AppDelegate.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit
import CoreData
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "smartFinance")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

 

SceneDelegate.swift

//
//  SceneDelegate.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.

        // Save changes in the application's managed object context when the application transitions to the background.
        (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
    }


}

 

ViewController.swift

//
//  ViewController.swift
//  smartFinance
//
//  Created by     on 2020/06/01.
//  Copyright © 2020 dream. All rights reserved.
//

import UIKit
import Firebase

class ViewController: UIViewController {

    @IBOutlet weak var m_id: UITextField!
    @IBOutlet weak var m_pwd: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func tapLogin(_ sender: Any) {
        Auth.auth().signIn(withEmail: m_id.text!, password: m_pwd.text!) { [weak self] authResult, error in
          guard let strongSelf = self else { return }
          // ...
            print(strongSelf)
        }
    }
    @IBAction func tapSignUp(_ sender: Any) {
//            m_id.text
//            m_pwd.text
        Auth.auth().createUser(withEmail: m_id.text!, password: m_pwd.text!) { authResult, error in
          // ...
            print(authResult)
        }
    }
}

 

+ Recent posts