这篇会来教大家如何透过 Firebase 在你的 iOS App 上实作注册以及登入功能
透过 Firebase 在你的 iOS App 上实作登出以及密码重设功能会放在下一篇喔
打开专案的 Podfile,新增 Firebase/Auth
pod 'Firebase/Auth'
pod install
接着到该专案的 Firebase Console 里点左侧的「Authentication」,再点「Sign-in method」,将「电子邮件/密码」这个选项开启
打开 专案名称.xcworkspace
,然後在你需要用到的档案引入 Firebase
import Firebase
import FirebaseAuth
首先先将帐号跟密码的 TextField、帐号登入的 Button 的 IBOutlet 拉好
以及宣告一个变数 isSignIn,型别为 Bool,初始值为 false,用来判断是否已经登入
@IBOutlet weak var accountTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var signInOrSignOutBtn: UIButton!
var isSignIn: Bool = false
然後在注册帐号按钮的 IBAction 加入下面这段
我们先判断是否任一帐号栏位为空,为空的话,就通知说「请输入帐号!」
不为空的话,就透过 Firebase 提供的 createUser() API,来实作注册帐号功能
@IBAction func registerAccount(_ sender: UIButton) {
if (accountTF.text == "") {
CustomFunc.customAlert(title: "请输入帐号!", message: "", vc: self, actionHandler: nil)
} else {
Auth.auth().createUser(withEmail:accountTF.text!, password: passwordTF.text!) { (user, error) in
if (error == nil) {
CustomFunc.customAlert(title: "帐号已成功建立!", message: "", vc: self, actionHandler: nil)
} else {
CustomFunc.customAlert(title: "", message: "\(String(describing: error!.localizedDescription))", vc: self, actionHandler: nil)
}
}
}
}
注册完之後,就可以在 Firebase Console 里看到刚刚我们注册的帐号了
接着在帐号登入按钮的 IBAction 加入下面这段
我们先判断目前是否有使用者存在
假设有的话,就执行帐号登出功能,没有的话,就执行帐号登入功能,这里我们先实作帐号登入功能
接着我们先判断是否任一帐号密码栏位为空,为空的话,就通知说「请重新输入帐号密码!」
不为空的话,就透过 Firebase 提供的 signIn() API,来实作帐号登入功能
@IBAction func accountSignInOrSignOut(_ sender: UIButton) {
if (Auth.auth().currentUser == nil || !isSignIn) {
// 无用户登入
if (accountTF.text == "" || passwordTF.text == "") {
CustomFunc.customAlert(title: "请重新输入帐号密码!", message: "", vc: self, actionHandler: nil)
} else {
Auth.auth().signIn(withEmail:accountTF.text!, password: passwordTF.text!) { (user, error) in
guard error == nil else {
CustomFunc.customAlert(title: "", message: "\(String(describing: error!.localizedDescription))", vc: self, actionHandler: nil)
return
}
CustomFunc.customAlert(title: "登入成功!", message: "", vc: self, actionHandler: self.getFirebaseUserInfo)
self.accountTF.text = ""
self.passwordTF.text = ""
self.isSignIn = true
self.signInOrSignOutBtn.setTitle("帐号登出", for: .normal)
}
}
} else {
// 有用户登入
// 登出功能,下一篇才会教喔!
}
}
帐号登出、密码重设功能就留到明天再说罗~
本篇的参考范例程序码:Github
<<: 从零开始的8-bit迷宫探险【Level 19】这个相遇我等了一辈子了-侦测主角与怪物接触
>>: 从 JavaScript 角度学 Python(26) - 指定直译器
量化交易30天 本系列文章是纪录一位量化交易新手的学习过程,除了基础的Python语法不说明,其他...
Docker 资料保存 Docker内空间的资料能不能保存下来? 当我关闭一个Container後下...
一直以来,我们使用 TeamCity 时都是透过 Web UI 来设定,不论 Project 的 V...
问题回答 teleport 是 Vue 3 新增功能。teleport 就像是多啦A梦的「随意门」一...
接下来就可以利用上面的 meta-annotation 去定义我们的属性。 @Target(Anno...