포스트

Final (26)

프로필 수정에서 닉네임 중복 확인

변경 후

프로필 편집 화면에서 닉네임 변경 시 중복 확인 기능이 도입되었다.
사용자는 “중복확인” 버튼을 눌러 닉네임 사용 가능 여부를 확인하고, 검사를 통과해야만 저장이 가능하다.


주요 추가 요소 및 설명

  • validateButton: 중복 확인 버튼을 눌러 검사 트리거
  • validateLabel: 검사 결과 메시지 시각화
  • isValidate: 중복 확인 통과 여부를 저장하는 플래그
  • validateName(): Combine을 통해 사용자 목록 조회 및 비교
  • saveChanges(): 저장 전 isValidate 값 확인

validateButton 및 validateLabel UI 정의

중복 확인 버튼과 상태 메시지를 라벨로 구현하고 setupUserNameTextField() 내부에 배치하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let validateButton: UIButton = {
    let button = UIButton()
    button.setTitle("중복확인", for: .normal)
    button.addTarget(self, action: #selector(validateName), for: .touchUpInside)
    button.titleLabel?.font = ThemeFont.fontBold(size: 14)
    button.titleLabel?.textColor = .white
    button.backgroundColor = ThemeColor.mainOrange
    button.layer.cornerRadius = 10
    return button
}()

lazy var validateLabel: UILabel = {
    let label = UILabel()
    label.font = ThemeFont.fontBold(size: 18)
    label.textColor = ThemeColor.mainBlack
    label.text = "닉네임 변경 전 중복확인 검사를 해주세요."
    return label
}()

validateName() 구현 - Combine을 이용한 닉네임 검사

전체 유저 데이터를 Combine으로 가져온 후, 사용자가 입력한 닉네임과 비교하여 중복 여부를 검사한다.
결과는 validateLabel의 색상과 텍스트로 시각화된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@objc func validateName() {
    let manageManager = ManageManager()
    viewModel = ManageViewModel(manageManager: manageManager)
    
    viewModel.getUsers()
    
    guard let nickName = userNameTextField.text else { return }
    
    viewModel.$userArray.sink { [weak self] modelArray in
        if modelArray.contains(where: { $0.nickName == nickName }) {
            self?.isValidate = false
            self?.validateLabel.textColor = .red
            self?.validateLabel.text = "이미 닉네임이 존재합니다."
        } else {
            self?.isValidate = true
            self?.validateLabel.textColor = .blue
            self?.validateLabel.text = "입력하신 닉네임은 사용 가능합니다."
        }
    }.store(in: &cancellables)
}

saveChanges() - 중복확인 여부 기반 저장 제어

닉네임 저장 전 isValidate 값이 true인지 검사한다.
검사 전이라면 Alert로 유도하고, true일 경우만 updateProfile을 호출한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@objc func saveChanges() {
    if isValidate {
        ProgressHUD.animate()
        guard let uid = Auth.auth().currentUser?.uid else { return }
        var selectedImage = profileImage
        var userName = userNameTextField.text
        
        if userName == "" {
            userName = profileName
        }
        
        if selectedImage == nil {
            KingfisherManager.shared.retrieveImage(with: URL(string: gotProfileImage!)!) { [weak self] result in
                switch result {
                case .success(let image):
                    selectedImage = image.image
                case .failure(let error):
                    self?.showMessage(title: "에러 발생", message: "\(error)가 발생했습니다")
                }
            }
        }
        
        userManager.updateProfile(uid: uid, nickName: userName!, profile: selectedImage!) { [weak self] result in
            switch result {
            case .success(()):
                ProgressHUD.dismiss()
                self?.showMessage(title: "수정 완료", message: "프로필 정보가 수정 되었습니다.") {
                    self?.navigationController?.popViewController(animated: true)
                }
            case .failure(let error):
                ProgressHUD.dismiss()
                self?.showMessage(title: "에러 발생", message: "\(error.localizedDescription)가 발생했습니다.")
            }
        }
    } else {
        showMessage(title: "중복확인을 해주세요", message: "닉네임 중복확인을 먼저 해주세요.")
    }
}

정리

  • 중복 확인은 명시적으로 사용자가 클릭해야 진행되도록 구현
  • Combine의 sink를 활용한 실시간 유저 데이터 비교
  • 닉네임이 중복되지 않는 경우에만 저장 가능하도록 로직 제한
  • 저장 로직에서 중복검사 결과(isValidate)를 강제 조건으로 활용하여 UX 안정성 확보

예외처리

핵심 변경 사항

  • currentUser / customUser 조건 처리
    • ChatVC 전환 시 User 또는 CustomUser 타입에 따라 ViewController를 다르게 초기화함
    • 인증된 유저일 경우 닉네임 유효성(isValidate) 검사 후 채팅 가능
  • 닉네임 중복 검증 기능 추가
    • ManageViewModel을 사용하여 Firebase RealtimeDatabase에서 유저 목록을 조회
    • 동일 닉네임이 존재할 경우 다시 입력을 요구하는 알림창 반복 표시
  • 예외 처리 강화
    • 닉네임이 설정되지 않았을 경우 채팅 진입을 막고 Alert을 통해 입력을 유도
    • Combine을 통해 닉네임 유효 여부를 비동기로 처리

주요 코드 설명

닉네임 유효성 검증 로직:

1
2
3
4
5
6
7
8
9
validateNickname(nickName:completion:) {
  viewModel.getUsers {
    if 중복 없음 {
      completion(true)
    } else {
      completion(false)
    }
  }
}

채팅방 진입 전 조건 처리:

1
2
3
4
5
6
7
8
9
10
11
if let user = currentUser {
  if isValidate {
    viewController = ChatVC(user: user, channel: channel)
    viewController?.isLocation = isLocation
  } else {
    showNameAlert(uid: uid)
    return
  }
} else if let customUser = customUser {
  viewController = ChatVC(customUser: customUser, channel: channel)
}

닉네임 입력 유도 Alert:

1
2
3
4
showNameAlert(uid:) {
  UIAlertController(title: "Enter Name", ...)
  닉네임이 중복되면 showNameAlert 재호출
}
  • 인증 유저 여부 및 닉네임 상태에 따라 채팅 진입 흐름을 엄격히 관리
  • UIKit 환경에서 Combine과 MVVM 패턴을 적절히 활용하여 안정적인 흐름 구현

Json 사용

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.