Posted at

UserDefaultsを使って簡単なログイン機能

初心者です。ログイン機能を作ったので、メモとして残す。

・Rxを使って文字を更新を感知して、ログインボタンのステータスを変える。あと文字数も制限。


LoginViewController.swift

import UIKit

import RxSwift
import RxCocoa

final class LoginViewController: UIViewController {

@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
private let disposeBag = DisposeBag()
private let userdefaulse = UserDefaults.standard

override func viewDidLoad() {
super.viewDidLoad()
initView()
}

private func initView() {
TextFieldObserver(nameTextField)
TextFieldObserver(passwordTextField)
ChangeLoginbutton()
}

private func TextFieldObserver(_ textField: UITextField) {
textField.rx.text.subscribe(onNext: { text in
if let text = text {
textField.text = text.prefix(15).description
}
self.ChangeState()
}).disposed(by: disposeBag)
}

private func ChangeLoginbutton() {
loginButton.addTarget(self, action: #selector(Login), for: .touchUpInside)
loginButton.setTitleColor(.white, for: .normal)
loginButton.setTitleColor(.darkGray, for: .disabled)
}

private func ChangeState() {
if nameTextField.text?.isEmpty == false,
passwordTextField.text?.isEmpty == false {
loginButton.isEnabled = true
loginButton.backgroundColor = UIColor(hex: "b8860b")
} else {
loginButton.isEnabled = false
loginButton.backgroundColor = UIColor(hex: "708090")
}
}

@IBAction private func TransitonToSignUp(_ sender: UIButton) {
self.performSegue(withIdentifier: "SignUpView", sender: nil)
}

@objc private func Login() {

guard let name = nameTextField.text else { return }
guard let pw = passwordTextField.text else { return }

let userName = userdefaulse.string(forKey: "name")
let userPw = userdefaulse.string(forKey: "password")

if name == userName && pw == userPw {

userdefaulse.set(true, forKey: "userLoginState")
let alert = UIAlertController(title: "成功", message: "ログインしました", preferredStyle:.alert)
let action = UIAlertAction(title: "OK", style: .default) {
action in self.performSegue(withIdentifier: "TopView", sender: nil)
}
alert.addAction(action)
self.present(alert,animated: true)
} else {
let alert = UIAlertController(title: "警告", message: "名前かパスワードが違います", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alert.addAction(action)
self.present(alert, animated: true)
}
}
}



SignUpViewController.swift

import UIKit

import RxCocoa
import RxSwift

final class SignUpViewController: UIViewController {

@IBOutlet weak var NameTextField: UITextField!
@IBOutlet weak var PassWordTextField: UITextField!
@IBOutlet weak var PassWordConfirmationTextField: UITextField!
@IBOutlet weak var signUpButton: UIButton!
private let disposeBag = DisposeBag()
private let userdefaulse = UserDefaults.standard

override func viewDidLoad() {
super.viewDidLoad()
initView()
}

private func initView() {
TextFieldObserver(NameTextField)
TextFieldObserver(PassWordTextField)
TextFieldObserver(PassWordConfirmationTextField)
ChangeSignUpButton()
ChangeState()

}

private func TextFieldObserver(_ textField: UITextField) {
textField.rx.text.subscribe(onNext: { text in
if let text = text {
textField.text = text.prefix(15).description
}
self.ChangeState()
}).disposed(by: disposeBag)
}

private func ChangeSignUpButton() {
signUpButton.addTarget(self, action: #selector(SignUp), for: .touchUpInside)
signUpButton.setTitleColor(.white, for: .normal)
signUpButton.setTitleColor(.darkGray, for: .disabled)
}

private func ChangeState() {
if NameTextField.text?.isEmpty == false,
PassWordTextField.text?.isEmpty == false,
PassWordConfirmationTextField.text?.isEmpty == false {
signUpButton.isEnabled = true
signUpButton.backgroundColor = UIColor(hex: "1e90ff")
} else {
signUpButton.isEnabled = false
signUpButton.backgroundColor = UIColor(hex: "708090")
}
}

@objc private func SignUp() {

guard let name = NameTextField.text else { return }
guard let pw = PassWordTextField.text else { return }
guard let pwc = PassWordConfirmationTextField.text else { return }

if pw != pwc{
let alert = UIAlertController(title: "警告", message: "パスワードが一致しません", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alert.addAction(action)
self.present(alert, animated: true)
return
}

userdefaulse.set(name, forKey: "name")
userdefaulse.set(pw, forKey: "password")
userdefaulse.set(true, forKey: "userLoginState")
let alert = UIAlertController(title: "成功", message: "登録が成功しました", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) {
action in self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
self.present(alert, animated: true)
}
}


一旦、ログアウトだけ。

ここからチャット機能を追加したい。

ログアウト押すとuserdefaultsにfalseをセットする。


ViewController.swift

import UIKit

class ViewController: UIViewController {

let userdefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()

}
override func viewDidAppear(_ animated: Bool) {
let userLoginState = userdefaults.bool(forKey: "userLoginState")
print(userLoginState)
if (!userLoginState) {
self.performSegue(withIdentifier: "loginView", sender: nil)
}
}
@IBAction func Logout(_ sender: UIButton) {
userdefaults.set(false, forKey: "userLoginState")
self.performSegue(withIdentifier: "loginView", sender: nil)
}
}


ここは写経。

時間があるときに、じっくり調べる。


UIColor.Swift

import UIKit

extension UIColor {

convenience init(hex: String, alpha: CGFloat) {
let v = Int("000000" + hex, radix: 16) ?? 0
let r = CGFloat(v / Int(powf(256, 2)) % 256) / 255
let g = CGFloat(v / Int(powf(256, 1)) % 256) / 255
let b = CGFloat(v / Int(powf(256, 0)) % 256) / 255
self.init(red: r, green: g, blue: b, alpha: min(max(alpha,0 ),1))
}

convenience init(hex: String) {
self.init(hex: hex, alpha: 1.0)
}
}


参考記事

RxSwift

https://qiita.com/Narakkyyyyy/items/39e76cfd188b1595293f

Userdefaults

https://qiita.com/TakayukiNJ/items/63ade09400db8593eff0