728x90
SMALL
import UIKit
class AlertManager {
private static func showBasicAlert(on vc: UIViewController, with title: String, and message: String?) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
vc.present(alert, animated: true)
}
}
}
// MARK: - Extension: Show Validation Alerts
extension AlertManager {
public static func showInvalidEmailAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Invalid Email", and: "Please enter a valid email address.")
}
public static func showInvalidPasswordAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Invalid Password", and: "Please enter a valid password.")
}
public static func showInvalidUsernameAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Invalid Username", and: "Please enter a valid username.")
}
}
// MARK: - Extension: Log In Errors
extension AlertManager {
public static func showSignInErrorAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Unknown Error Signing In", and: nil)
}
public static func showSignInErrorAlert(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Error Signing In", and: "\(error.localizedDescription)")
}
}
// MARK: - Extension: Log Out Errors
extension AlertManager {
public static func showLogoutErrorAlert(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Log out Error", and: "\(error.localizedDescription)")
}
}
// MARK - Extension: Forgot Errors
extension AlertManager {
public static func showPasswordResetSent(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Password Reset Sent", and: nil)
}
public static func showErrorSendingPasswordReset(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Error Sending Password Reset", and: "\(error.localizedDescription)")
}
}
// MARK: - Extension: Fetching User Errors
extension AlertManager {
public static func showFetchingUserError(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Error Fetching User", and: "\(error.localizedDescription)")
}
public static func showUnknownFetchingUserError(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Unknown Error Fetching User", and: nil)
}
}
위의 코드는 AlertManager라는 이름의 유틸리티 클래스를 정의하여 iOS 앱에서 다양한 경고(Alert)를 간편하게 관리하고 표시할 수 있도록 설계된 코드입니다. 이 클래스는 주로 사용자 입력 검증, 로그인/로그아웃 관련 오류 처리, 비밀번호 재설정 및 사용자 데이터 가져오기와 관련된 경고 메시지를 표시하는 데 사용됩니다.
주요 구성 요소
1. showBasicAlert (핵심 메서드)
private static func showBasicAlert(on vc: UIViewController, with title: String, and message: String?) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
vc.present(alert, animated: true)
}
}
- 역할:
- 경고(Alert)를 표시하는 기본적인 기능을 제공합니다.
- UIAlertController를 생성하여 지정된 UIViewController 위에 표시합니다.
- 매개변수:
- vc: 알림을 표시할 UIViewController.
- title: 경고창의 제목.
- message: 경고창의 메시지 (옵션).
- 주요 구현:
- DispatchQueue.main.async: UI 업데이트는 반드시 메인 스레드에서 이루어져야 하므로 메인 큐에서 실행.
- UIAlertController: 경고 창을 생성.
- addAction: "Dismiss" 버튼을 추가하여 경고를 닫을 수 있게 함.
- present: 전달받은 뷰 컨트롤러에서 경고 창을 표시.
2. AlertManager Extensions
AlertManager는 다양한 시나리오에 맞는 경고 메시지를 제공하기 위해 여러 확장을 통해 구체적인 메서드를 추가합니다. 각 메서드는 내부적으로 showBasicAlert를 호출하여 기본 알림을 표시합니다.
AlertManager 기능별 확장
1. Validation Alerts
입력 검증과 관련된 경고를 처리합니다.
extension AlertManager {
public static func showInvalidEmailAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Invalid Email", and: "Please enter a valid email address.")
}
public static func showInvalidPasswordAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Invalid Password", and: "Please enter a valid password.")
}
public static func showInvalidUsernameAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Invalid Username", and: "Please enter a valid username.")
}
}
- 이메일, 비밀번호, 사용자 이름의 입력값이 유효하지 않을 때 호출.
- 각 경고는 제목과 메시지가 다르며, 사용자에게 입력값 수정 요청.
2. Log In Errors
로그인 실패와 관련된 경고를 처리합니다.
extension AlertManager {
public static func showSignInErrorAlert(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Unknown Error Signing In", and: nil)
}
public static func showSignInErrorAlert(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Error Signing In", and: "\(error.localizedDescription)")
}
}
showSignInErrorAlert:
- 로그인 중 발생한 오류를 표시.
- 오버로드:
- 오류가 없는 일반 경고.
- Error 객체를 포함하여 오류 메시지를 상세히 표시.
3. Log Out Errors
로그아웃 중 발생한 오류를 처리합니다.
extension AlertManager {
public static func showLogoutErrorAlert(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Log out Error", and: "\(error.localizedDescription)")
}
}
- 로그아웃 중 문제가 발생했을 때 Error 객체의 메시지를 표시.
4. Forgot Password Errors
비밀번호 재설정과 관련된 경고를 처리합니다.
extension AlertManager {
public static func showPasswordResetSent(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Password Reset Sent", and: nil)
}
public static func showErrorSendingPasswordReset(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Error Sending Password Reset", and: "\(error.localizedDescription)")
}
}
- showPasswordResetSent:
- 비밀번호 재설정 요청이 성공적으로 전송되었음을 알림.
- showErrorSendingPasswordReset:
- 비밀번호 재설정 요청 중 발생한 오류를 알림.
5. Fetching User Errors
사용자 정보 가져오기 중 발생한 오류를 처리합니다.
extension AlertManager {
public static func showFetchingUserError(on vc: UIViewController, with error: Error) {
self.showBasicAlert(on: vc, with: "Error Fetching User", and: "\(error.localizedDescription)")
}
public static func showUnknownFetchingUserError(on vc: UIViewController) {
self.showBasicAlert(on: vc, with: "Unknown Error Fetching User", and: nil)
}
}
- showFetchingUserError:
- Error 객체를 통해 사용자 데이터를 가져오는 데 발생한 문제를 알림.
- showUnknownFetchingUserError:
- 알 수 없는 오류 발생 시 간단한 경고 메시지 표시.
장점
- 코드 재사용성:
- showBasicAlert를 통해 경고 메시지의 기본 동작을 통합.
- 다양한 상황에 대해 공통된 메서드를 확장해 재사용성 향상.
- 유지보수성:
- 오류나 경고 메시지를 한 곳에서 관리할 수 있어 수정이 용이.
- 유연성:
- 각 확장에서 구체적인 경고를 정의해 상황에 맞는 메시지를 표시 가능.
- UI 작업 안정성:
- DispatchQueue.main.async를 사용해 메인 스레드에서 경고를 처리하므로 앱이 UI 작업 중 충돌하지 않음.
🔥 showBasicAlert 메서드를 static 으로 선언한 이유 🔥
1. 인스턴스화 없이 사용 가능
- static 메서드는 클래스 자체에서 직접 호출할 수 있습니다.
- AlertManager는 경고 메시지를 보여주는 유틸리티 클래스로 설계되었으므로, 인스턴스를 생성하지 않고 바로 사용할 수 있도록 설계되었습니다.
AlertManager.showBasicAlert(on: viewController, with: "Title", and: "Message")
- AlertManager의 객체를 생성하지 않아도 바로 메서드를 호출할 수 있습니다.
- 이를 통해 사용 편의성과 코드 간결성을 제공합니다.
2. 상태를 가지지 않는 메서드
- showBasicAlert는 클래스의 상태(프로퍼티)에 의존하지 않고, 전달받은 매개변수(vc, title, message)만으로 동작합니다.
- 즉, 이 메서드는 순수 함수(pure function)에 가까우며, 상태가 필요 없으므로 인스턴스 메서드로 만들 이유가 없습니다.
3. 메모리 사용 최적화
- static 메서드는 클래스 레벨에서 관리되며, 메서드를 호출할 때마다 인스턴스를 생성하지 않으므로 메모리 사용이 더 효율적입니다.
- 유틸리티 클래스처럼 전역적으로 여러 곳에서 호출될 가능성이 높은 경우, static 메서드는 메모리 낭비를 줄이는 데 도움이 됩니다.
4. 코드 구조의 명확성
- AlertManager는 상태를 가지는 객체라기보다는, 특정 기능(알림 표시)을 제공하는 도구적 역할을 합니다.
- static 메서드로 설계하면 클래스 자체가 단순히 유틸리티 역할을 한다는 의도를 더 명확히 전달할 수 있습니다.
5. 사용 사례에 적합
- showBasicAlert는 특정 경고를 화면에 표시하는 단일 작업을 수행합니다.
- 이런 작업은 인스턴스를 생성하지 않고 전역적으로 호출하는 것이 일반적입니다.
static 메서드와 instance 메서드 비교
| 특징 | static 메서드 | instance 메서드 |
| 호출 방법 | 클래스 이름으로 직접 호출 (AlertManager.showBasicAlert) | 인스턴스를 생성해야 호출 가능 (instance.showBasicAlert) |
| 상태 의존성 | 클래스의 상태나 인스턴스 상태에 의존하지 않음 | 인스턴스 변수나 프로퍼티에 의존 가능 |
| 메모리 사용 | 메서드 자체는 클래스 레벨에서 관리되므로 효율적 | 호출마다 인스턴스를 생성해야 할 수 있음 |
| 유틸리티 클래스에 적합 | ✔ | ✘ (불필요한 인스턴스 생성으로 비효율적) |
728x90
LIST
'Project > FirebaseTest' 카테고리의 다른 글
| FireBase - 로그인과 로그아웃 처리하는 메서드 정의 (1) | 2024.12.03 |
|---|---|
| FireBase - 사용자 등록 기능 (0) | 2024.12.03 |
| FireBase - UITextView with open WKWebView (0) | 2024.12.03 |
| FireBase - Webkit (1) | 2024.12.03 |
| FireBase - 커스텀 버튼, 뷰, 텍스트 필드에 대해 (0) | 2024.12.02 |