Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat][fix] 코어데이터 에러 디버깅 문구 추가, 100자 초과 시 빨간색으로 변경 #165

Merged
merged 2 commits into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 27 additions & 45 deletions Happiggy-bank/Happiggy-bank/CoreData/PersistenceStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class PersistenceStore {
static var shared: PersistenceStore = {
PersistenceStore(name: StringLiteral.sharedPersistenceStoreName)
}()

static private(set) var fatalErrorNeeded = false

/// persistence container 의 viewContext 에 접근하기 위한 syntactic sugar
Expand Down Expand Up @@ -68,25 +68,28 @@ class PersistenceStore {

// MARK: - Core Data Saving support

/// 현재 context 를 저장, 에러가 발생하면 설정한 에러 메시지(기본은 에러 이름)를 출력함
func save(errorMessage: String? = nil) {
/// 현재 context 를 저장, 에러가 발생하면 발생한 에러 메시지(기본은 에러 이름)를 출력함
@discardableResult
func save() -> (String, String)? {
if self.context.hasChanges {
do {
try self.context.save()
return nil

} catch {
let nserror = error as NSError
if let errorMessage = errorMessage {
print("\(errorMessage)+\(nserror.localizedDescription)+\(nserror.userInfo)")
} else {
print("\(nserror.localizedDescription), \(nserror.userInfo)")
}

self.presentErrorAlert(
title: StringLiteral.saveErrorTitle,
message: StringLiteral.saveErrorMessage
)
let title = StringLiteral.saveErrorTitle
let message = """
\(StringLiteral.saveErrorMessage)
\(nserror.localizedDescription)
\(nserror.localizedFailureReason ?? .empty)
\(nserror.userInfo)
"""
return (title, message)
}
}
return nil
}


Expand All @@ -113,43 +116,22 @@ class PersistenceStore {

// MARK: - Alert

/// 작업 실패 시 알림
private func presentErrorAlert(
/// 알림
func makeErrorAlert(
title: String?,
message: String?,
handler: ((UIAlertAction) -> Void)? = nil
) {
let alert = self.makeErrorAlert(
title: title,
message: message,
handler: handler
)
self.windowScene?.topMostViewController?.present(alert, animated: true)
}

/// 알림 생성
private func makeErrorAlert(
title: String?,
message: String?,
handler: ((UIAlertAction) -> Void)? = nil
confirmHandler: ((UIAlertAction) -> Void)? = nil
) -> UIAlertController {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .alert
)

let confirmationAction = UIAlertAction(
let confirmAction = UIAlertAction.confirmAction(
title: StringLiteral.okButtonTitle,
style: .default
) { action in
guard let handler = handler
else { return }

handler(action)
}

alert.addAction(confirmationAction)
return alert
handler: confirmHandler
)

return UIAlertController.basic(
alertTitle: title,
alertMessage: message,
confirmAction: confirmAction
)
}
}
2 changes: 1 addition & 1 deletion Happiggy-bank/Happiggy-bank/Utils/Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,7 @@ extension NewNoteTextViewModel {
static let textViewNote = "textViewNote"

/// 글자수 라벨 텍스트를 반환
static let letterCountText = " \\ \(NewNoteTextViewController.Metric.noteTextMaxLength)"
static let letterCountText = " / \(NewNoteTextViewController.Metric.noteTextMaxLength)"
}

/// NewNoteTextViewModel 에서 사용하는 폰트 크기
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,10 @@ final class BottleMessageViewController: UIViewController {

self.tapGestureRecognizer.isEnabled.toggle()
HapticManager.instance.selection()
self.saveBottleUpdatesAndDismiss()
guard self.saveBottleUpdates() == true
else { return }

self.dismissWithAnimation()
}


Expand Down Expand Up @@ -179,19 +182,37 @@ final class BottleMessageViewController: UIViewController {
}

/// 저금통 상태를 업데이트하고 다른 뷰 컨트롤러로 이동
private func saveBottleUpdatesAndDismiss() {
private func saveBottleUpdates() -> Bool {
self.bottle.isOpen.toggle()


if self.bottle.notes.isEmpty {
PersistenceStore.shared.delete(self.bottle)
}

guard let (errorTitle, errorMessage) = PersistenceStore.shared.save()
else { return true }

let alert = PersistenceStore.shared.makeErrorAlert(
title: errorTitle,
message: errorMessage
) { _ in
self.dismiss(animated: false)
self.fadeOut()
}

self.present(alert, animated: true)
return false
}

/// 애니메이션과 함께 홈뷰/쪽지리스트로 이동
private func dismissWithAnimation() {
if !self.bottle.notes.isEmpty {
self.moveToNoteListWithAnimation()
}

if self.bottle.notes.isEmpty {
PersistenceStore.shared.delete(self.bottle)
self.dismiss(animated: false)
self.fadeOut()
}

PersistenceStore.shared.save()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ final class BottleNameEditViewController: UIViewController {
return
}

saveBottleData(with: text)
guard saveBottleData(with: text) == true
else { return }

self.dismiss(animated: true)
}

Expand Down Expand Up @@ -117,10 +119,22 @@ final class BottleNameEditViewController: UIViewController {

// MARK: Functions

private func saveBottleData(with text: String) {
private func saveBottleData(with text: String) -> Bool {
self.bottle.title = text
self.bottle.hasFixedTitle = true
PersistenceStore.shared.save()

guard let (errorTitle, errorMessage) = PersistenceStore.shared.save()
else { return true }

let alert = PersistenceStore.shared.makeErrorAlert(
title: errorTitle,
message: errorMessage
) { _ in
self.dismiss(animated: false)
}

self.present(alert, animated: true)
return false
}


Expand Down Expand Up @@ -209,7 +223,9 @@ extension BottleNameEditViewController: UITextFieldDelegate {
return true
}

saveBottleData(with: text)
guard saveBottleData(with: text) == true
else { return false }

self.dismiss(animated: true)
return true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ final class NewBottleMessageFieldViewController: UIViewController {
// MARK: Functions

/// 새 저금통 저장하는 메서드
private func saveNewBottle() {
private func saveNewBottle() -> Bool {
guard let title = self.bottleData?.name,
let endDate = self.bottleData?.endDate
else { return }
else { return true }

if let openMessage = self.bottleData.openMessage {
_ = Bottle(
Expand All @@ -87,7 +87,22 @@ final class NewBottleMessageFieldViewController: UIViewController {
)
}

PersistenceStore.shared.save()
guard let (errorTitle, errorMessage) = PersistenceStore.shared.save()
else { return true }

let alert = PersistenceStore.shared.makeErrorAlert(
title: errorTitle,
message: errorMessage
) { _ in
self.fadeOut()
self.performSegue(
withIdentifier: SegueIdentifier.unwindFromNewBottlePopupToHomeView,
sender: self
)
}

self.present(alert, animated: true)
return false
}


Expand Down Expand Up @@ -134,7 +149,9 @@ final class NewBottleMessageFieldViewController: UIViewController {
let confirmAction = UIAlertAction.confirmAction(
title: StringLiteral.confirmationAlertConfirmButtonTitle
) { _ in
self.saveNewBottle()
guard self.saveNewBottle() == true
else { return }

self.performSegue(
withIdentifier: SegueIdentifier.unwindFromNewBottlePopupToHomeView,
sender: self
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ final class NewNoteTextViewController: UIViewController {
self.yearLabel.textColor = self.viewModel.labelColor
self.monthAndDayLabel.textColor = self.viewModel.labelColor
self.letterCountLabel.textColor = self.viewModel.labelColor
self.letterCountLabel.attributedText = self.viewModel.attributedLetterCountString(
count: self.textView.text.count
)
}

/// 새로운 노트 엔티티를 생성
Expand All @@ -219,11 +222,20 @@ final class NewNoteTextViewController: UIViewController {
)
}

/// 새로 생성한 노트 엔티티를 저장하고 알림을 포스트
private func saveAndPostNewNote(_ note: Note) {
let noteAndDelay = (note: note, delay: CATransition.transitionDuration)
self.post(name: .noteDidAdd, object: noteAndDelay)
PersistenceStore.shared.save()
/// 새로 생성한 노트 엔티티를 저장하고 성공 여부에 따라 불 리턴
private func saveAndPostNewNote() -> Bool {
guard let (errorTitle, errorMessage) = PersistenceStore.shared.save()
else { return true }

let alert = PersistenceStore.shared.makeErrorAlert(
title: errorTitle,
message: errorMessage
) { _ in
self.dismissWithAnimation()
}
self.present(alert, animated: true)

return false
}

/// 쪽지 저장 의사를 재확인 하는 알림을 띄움
Expand All @@ -234,38 +246,40 @@ final class NewNoteTextViewController: UIViewController {

/// 쪽지 저장 의사를 재확인하는 알림 생성
private func makeConfirmationAlert() -> UIAlertController {
let alert = UIAlertController(
title: StringLiteral.alertTitle,
message: StringLiteral.message,
preferredStyle: .alert
)

let confirmAction = UIAlertAction(
title: StringLiteral.confirmButtonTitle,
style: .default) { _ in

let note = self.makeNewNote()

self.saveAndPostNewNote(note)
self.fadeOut()
self.performSegue(
withIdentifier: SegueIdentifier.unwindFromNoteTextViewToHomeView,
sender: note
)
}

let cancelAction = UIAlertAction(
title: StringLiteral.cancelButtonTitle,
style: .cancel) { _ in
self.textView.becomeFirstResponder()
}
let confirmAction = UIAlertAction.confirmAction(
title: StringLiteral.confirmButtonTitle
) { _ in

let note = self.makeNewNote()

guard self.saveAndPostNewNote() == true
else { return }

let noteAndDelay = (note: note, delay: CATransition.transitionDuration)
self.post(name: .noteDidAdd, object: noteAndDelay)
self.dismissWithAnimation()
}

alert.addAction(confirmAction)
alert.addAction(cancelAction)
let cancelAction = UIAlertAction.cancelAction { _ in
self.textView.becomeFirstResponder()
}

return alert
return UIAlertController.basic(
alertTitle: StringLiteral.alertTitle,
alertMessage: StringLiteral.message,
confirmAction: confirmAction,
cancelAction: cancelAction
)
}

/// 페이드아웃 효과와 함께 종료
private func dismissWithAnimation() {
self.fadeOut()
self.performSegue(
withIdentifier: SegueIdentifier.unwindFromNoteTextViewToHomeView,
sender: self
)
}


// MARK: - Navigation

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,13 @@ final class NewNoteTextViewModel {

/// 색깔 적용한 글자수 라벨 텍스트
func attributedLetterCountString(count: Int) -> NSMutableAttributedString {
let color = (count > NewNoteTextViewController.Metric.noteTextMaxLength) ?
UIColor.customWarningLabel : .noteHighlight(for: self.newNote.color)

let countString = "\(count)"
.nsMutableAttributedStringify()
.bold(fontSize: Font.letterCountLabel)
.color(color: .noteHighlight(for: self.newNote.color))
.color(color: color)

countString.append(StringLiteral.letterCountText.nsMutableAttributedStringify())

Expand Down