๐Ÿ”ฅํŒŒ์ด์–ด๋ฒ ์ด์Šค ๋กœ๊ทธ์ธ, ๋กœ๊ทธ์•„์›ƒํ•˜๊ธฐ

sangheeยท2021๋…„ 8์›” 9์ผ
0

๐Ÿ”ฅFirebase

๋ชฉ๋ก ๋ณด๊ธฐ
3/5
post-thumbnail

ObservableObject?

Apple Developer Documentation - ObservableObject

A type of object with a publisher that emits before the object has changed.

Published?

Apple Developer Documentation - Published

A type that publishes a property marked with an attribute.

๋ทฐ๋ชจ๋ธ

ViewModel์„ ๊ด€์ฐฐ์ด ๊ฐ€๋Šฅํ•˜๋„๋ก ObservableObject๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  currentUser๋ฅผ ์ €์žฅํ•œ๋‹ค.

class ViewModel: NSObject, ObservableObject {
    @Published var currentUser: FirebaseAuth.User?
}

๋กœ๊ทธ์ธ ํ•จ์ˆ˜ ๊ตฌํ˜„

์ด๋ฉ”์ผ๊ณผ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ด์šฉํ•ด ์ด๋ฉ”์ผ ๋กœ๊ทธ์ธ์„ ์‹œ๋„ํ•œ๋‹ค. error๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ์—๋Š” ์ถœ๋ ฅ์„ ํ•˜๊ณ  ๋๋‚˜๋„๋ก return์„ if๋ฌธ ๋‚ด๋ถ€์— ์ถ”๊ฐ€ํ•œ๋‹ค. result์—์„œ ์˜ต์…”๋„๋กœ ์กด์žฌํ•˜๋ฏ€๋กœ guard๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ user๋ฅผ ์ •์˜ํ•œ๋‹ค. ์ดํ›„ user๋ฅผ currentUser์— ํ• ๋‹นํ•œ๋‹ค.

func login(withEmail email: String, password: String) {
    Auth.auth().signIn(withEmail: email, password: password) { result, error in
        if let error = error {
            print("DEBUG: \(error.localizedDescription)")
            return
        }
        
        guard let user = result?.user else { return }
        self.currentUser = user
    }
}

๋กœ๊ทธ์•„์›ƒ ํ•จ์ˆ˜ ๊ตฌํ˜„

currentUser๋ฅผ ๋น„์›Œ ํ”„๋ก ํŠธ์—”๋“œ๋„ ์œ ์ €๊ฐ€ ์—†๋Š” ๊ฒƒ์„ ๋ฐ˜์˜ํ•˜๋„๋ก ํ•œ๋‹ค. ์•„๋ž˜์˜ ํ•จ์ˆ˜๋ฅผ ๋กœ๊ทธ์•„์›ƒ๋ฒ„ํŠผ๊ณผ ์•„๋ž˜์˜ ํ•จ์ˆ˜๋ฅผ ์—ฐ๊ฒฐํ•ด ์‚ฌ์šฉํ•œ๋‹ค.

func signOut() {
		self.currentUser = nil
		try? Auth.auth().signOut()
}

๊นƒํ—ˆ๋ธŒ ์ปค๋ฐ‹ ์ฃผ์†Œ

GitHub - Commit

profile
๐Ÿ‘ฉโ€๐Ÿ’ป

0๊ฐœ์˜ ๋Œ“๊ธ€