Skip to content

Commit

Permalink
Merge pull request #66 from 513sojin/feature/#64
Browse files Browse the repository at this point in the history
[#64] 기록하기 작성시 홈화면 이동
  • Loading branch information
88yhtserof authored Jul 23, 2022
2 parents d8caf03 + 62b2580 commit ee6dca9
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ enum CreateRecordConst {
static var dreamColorNum: Int?
static var isTouchedIndex: [Int] = []
static var genreIndex: [Int] = []
static var recordId: String?
}

class RecordViewController: BaseViewController {
Expand Down Expand Up @@ -170,6 +171,17 @@ class RecordViewController: BaseViewController {
var isCreateView: Bool = true
var emotionSelectedArray = [false, false, false, false, false, false]
// var reviseRecordInfo = [] // 서버에서 받아올 값. 모델이랑 매칭해주어야 함
var recordDetailData: RecordDetailModel?
var detailRecordId: String? {
didSet {
DispatchQueue.main.async {
self.navigationDetailView(id: self.detailRecordId ?? "")
}
}
}

var recordIdClosure: ((String) -> ())?


// MARK: - life cycle
override func viewDidLoad() {
Expand All @@ -188,30 +200,43 @@ class RecordViewController: BaseViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetStatus()
setReviseView()
setEditView()
setBackground()
}

// MARK: - Functions
private func setHeaderView() {
headerView.setHeaderView(HiddenMoreBtn: true, headerLabelText: "기록하기")
}

private func setReviseView() {
private func navigationDetailView(id: String) {
let detailVC = RecordDetailViewController()
navigationController?.pushViewController(detailVC, animated: true)
detailVC.recordID = id
}

private func setEditView() {
print("----------------------")
print(recordDetailData)
if !isCreateView { //MARK: - 수정하기 뷰인경우
//날짜, 제목 , 내용 , 감정, 꿈색상, 장르, 노트
headerView.headerLabel.text = "수정하기"
dateView.recordDateLabel.text = "2022-07-24"
titleTextField.text = "소진이당 ㅋㅋ"
contentTextView.text = "내용이당 ㅋㅋ"
noteTextView.text = "노트내용이다 ㅋㅋ"
CreateRecordConst.emotionNum = 4
CreateRecordConst.dreamColorNum = 3
CreateRecordConst.isTouchedIndex = [3]
dateView.recordDateLabel.text = recordDetailData?.date
titleTextField.text = recordDetailData?.title
contentTextView.text = recordDetailData?.content
noteTextView.text = recordDetailData?.note
CreateRecordConst.todayDate = Date()
CreateRecordConst.emotionNum = recordDetailData?.emotion
CreateRecordConst.dreamColorNum = recordDetailData?.dream_color
CreateRecordConst.isTouchedIndex = recordDetailData?.genre ?? [3]
contentLable.isHidden = true
setTitleTextField()
}
}

private func setBackground() {
view.backgroundColor = ColorType.darkBlue01.color
}

private func setDelegate() {
headerView.delegate = self
emotionCollectionView.delegate = self
Expand Down Expand Up @@ -311,32 +336,34 @@ class RecordViewController: BaseViewController {
}

@objc func saveButtonDidTap() {
print("saveButtonDidTap")
if let title = titleTextField.text {
if !title.isEmpty && !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
// MARK: - 저장 가능 상태
print("hoihihihihi")
guard let title = titleTextField.text,
let content = contentTextView.text,
let note = noteTextView.text else { return }

let date: String = CreateRecordConst.todayDate.toString()

print("---------------")
print(title)
print(content)
print(note)
print(CreateRecordConst.emotionNum)
print(CreateRecordConst.dreamColorNum)
print(CreateRecordConst.isTouchedIndex)
print(note)
print("---------------")

let record = CreateRecord(title: title, date: date, content: content, emotion: CreateRecordConst.emotionNum, dreamColor: CreateRecordConst.dreamColorNum, genre: CreateRecordConst.isTouchedIndex, note: note, voice: "62cdb868c3032f2b7af76531", writer: "62c9cf068094605c781a2fb9")

guard let emotionNum = CreateRecordConst.emotionNum,
let dreamNum = CreateRecordConst.dreamColorNum else { return }
let recordPut = PatchRecord(title: title, date: date, content: content, emotion: emotionNum, dreamColor: dreamNum, genre: CreateRecordConst.isTouchedIndex, note: note)
print("record: \(record)")

isCreateView ? postRecord(record: record) : putRecord(record: recordPut, id: "sojin")
// guard let emotionNum = CreateRecordConst.emotionNum,
// let dreamNum = CreateRecordConst.dreamColorNum,
// let id = recordDetailData?._id else { return }
//
// let recordPut = PatchRecord(title: title, date: date, content: content, emotion: emotionNum, dreamColor: dreamNum, genre: CreateRecordConst.isTouchedIndex, note: note)
// print("recordPut: \(recordPut)")
//
// print("isCreateView: \(isCreateView)")
// isCreateView ? postRecord(record: record) : putRecord(record: recordPut, id: id)
postRecord(record: record)
//
let tabVC = TabBarController()
navigationController?.pushViewController(tabVC, animated: true)
} else {
// MARK: - 저장 불가능 상태
UIView.animate(withDuration: 1.25, delay: 0.01, options: .curveEaseIn, animations: {
Expand All @@ -350,15 +377,11 @@ class RecordViewController: BaseViewController {

func setTitleTextField() {
if let title = titleTextField.text {
print("title : \(title)")
print(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
if !title.isEmpty && !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
// MARK: - 저장 가능 상태
print("저장 가능 상태")
saveButton.setImage(UIImage(named: ImageList.icnSaveOn.name), for: .normal)
} else {
// MARK: - 저장 불가능 상태
print("저장 불가능 상태")
saveButton.setImage(UIImage(named: ImageList.icnSaveOff.name), for: .normal)
}
}
Expand Down Expand Up @@ -574,16 +597,13 @@ extension RecordViewController: UICollectionViewDataSource, UICollectionViewDele
if collectionView == emotionCollectionView {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecordBarCollectionViewCell.reuseIdentifier, for: indexPath) as? RecordBarCollectionViewCell else { return UICollectionViewCell() }
if !isCreateView {
// cell.isSelected = false
print("isSelected - ")
if indexPath.item == CreateRecordConst.emotionNum {
print("안녕")
cell.updateRecordBarImage(reset: false)
}
} else {
print("isisisisisisisis")
}
// cell.recordBarImageView.alpha = 1
cell.setRecordBarImage(imageName: Constant.Emotion.IntType(indexPath.item + 1).title)
return cell
} else if collectionView == dreamColorCollectionView {
Expand Down Expand Up @@ -647,14 +667,32 @@ extension UILabel {
}

extension RecordViewController {
// func postRecord(record: CreateRecord) {
// Task {
// do {
// let recordData = try await createManager.postRequest(record: record)
// } catch {
// print("실패")
// }
// }
// }
//
// private func requestUserInformation() {
// MyPageService.shared.getUserInformation(completionHandler: { [weak self] data in
// guard let data = data as? UserInformationModel else { return }
// self?.userInformation = data
// })
// }
//
func postRecord(record: CreateRecord) {
Task {
do {
try await createManager.postRequest(record: record)
} catch {
print("실패")
}
}
createManager.postRequest(record: record, completionHandler: { [self] data in
guard let data = data as? DreamBaseModel else { return }
// guard let data = data.data?.id as? DataClass else { return }
guard let recordDataId = data.data?.id as? String else { return }
CreateRecordConst.recordId = data.data?.id
// print("postRecord: \(CreateRecordConst.recordId)")
// recordIdClosure?(CreateRecordConst.recordId ?? "")
})
}

func putRecord(record: PatchRecord, id: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import UIKit

class RecordDetailBottomSheetViewController: BaseViewController {
@IBOutlet weak var bottomSheetHeight: NSLayoutConstraint!
var recordDetailData: RecordDetailModel?

override func viewDidLoad() {
super.viewDidLoad()
Expand All @@ -27,6 +28,17 @@ class RecordDetailBottomSheetViewController: BaseViewController {
}
}

@IBAction func EditButtonTapped(_ sender: Any) {
print("수정하기")
let editRecordViewController = RecordViewController()
editRecordViewController.recordDetailData = recordDetailData
editRecordViewController.modalPresentationStyle = .overFullScreen
editRecordViewController.modalTransitionStyle = .crossDissolve
editRecordViewController.isCreateView = false

present(editRecordViewController, animated: true)
}

@IBAction func shareButtonDidTapped(_ sender: UIButton) {
guard let captureView = UINib(nibName: "RecordDetailViewController", bundle: nil).instantiate(withOwner: self, options: nil).first as? UIView
else { return }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class RecordDetailViewController: BaseViewController {
private var recordTitle = ""
private var recordDate = ""
var recordID: String? //TODO: - 화면 전환 시 기록 고유 번호 할당해주기
var recordDetailData: RecordDetailModel?
// var completionHandler: ((String) -> ())?

override func viewDidLoad() {
super.viewDidLoad()
Expand Down Expand Up @@ -115,6 +117,7 @@ extension RecordDetailViewController: NavigationBarDelegate {
func navigationMoreButtonDidTap() {
let recordDetailBottomSheet = RecordDetailBottomSheetViewController.instanceFromNib()
recordDetailBottomSheet.modalPresentationStyle = .overFullScreen
recordDetailBottomSheet.recordDetailData = recordDetailData

self.present(recordDetailBottomSheet, animated: false) {
recordDetailBottomSheet.showBottomSheet()
Expand All @@ -133,6 +136,10 @@ extension RecordDetailViewController {
RecordDetailService.shared.getRecordDetial(recordID: recordID, completionHandler: { [weak self] recordDetail in
guard let self = self else { return }
guard let recordDetail = recordDetail as? RecordDetailModel else { return }
self.recordDetailData = recordDetail

// self.completionHandler?(CreateRecordConst.recordId ?? "")

self.emotion = recordDetail.emotion
self.dreamColor = recordDetail.dream_color
self.genres = recordDetail.genre
Expand All @@ -145,6 +152,8 @@ extension RecordDetailViewController {
self.dateLabel.text = recordDetail.date
self.cardView.image = UIImage(named: Constant.DetailBackgroundColor.IntType(self.dreamColor).title)
}


})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@
<state key="normal" title="수정하기">
<color key="titleColor" name="white01"/>
</state>
<connections>
<action selector="EditButtonTapped:" destination="-1" eventType="touchUpInside" id="vcz-Rf-tJL"/>
</connections>
</button>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Wdu-wP-goO">
<rect key="frame" x="0.0" y="119" width="375" height="1"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ extension TabBarController: Presentable {
private func presentRecordView() {
let recordViewController = RecordViewController()
navigationController?.pushViewController(recordViewController, animated: false)
recordViewController.isCreateView = false
recordViewController.isCreateView = true
}

private func setTabBarItems() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import Foundation

protocol CreateRequestable: AnyObject {
func request(_ request: NetworkRequest) async throws -> [Record]
func postRequest(record: CreateRecord)
// func postRequest(record: CreateRecord) async throws -> DreamBaseModel
func postRequest(record: CreateRecord, completionHandler: @escaping (Any) -> Void)
func putRequset(record: PatchRecord, id: String)
}

Expand All @@ -24,7 +25,6 @@ final class CreateAPIManager: CreateRequestable {
guard let httpResponse = response as? HTTPURLResponse,
(200..<500) ~= httpResponse.statusCode
else { throw APIError.serverError }
print("httpResponse.statusCode: \(httpResponse.statusCode)")

let decodedData = try JSONDecoder().decode(Record.self, from: data)

Expand All @@ -35,8 +35,44 @@ final class CreateAPIManager: CreateRequestable {
}
}

func postRequest(record: CreateRecord) {
// func postRequest(record: CreateRecord) async throws -> DreamBaseModel {
// let url = URL(string: "http://13.125.138.47:8000/record")
// var request = URLRequest(url: url!)
// request.httpMethod = "POST"
//
// guard let uploadData = try? JSONEncoder().encode(record)
// else { throw APIError.urlEncodingError }
// request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// request.addValue("1", forHTTPHeaderField: "userId")
//
// let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
// if let data = data,
// let response = response as? HTTPURLResponse,
// (200..<500) ~= response.statusCode {
// print("response: \(response.statusCode)")
//
// guard let responseData = try? JSONDecoder().decode(DreamBaseModel.self, from: data) else {
// print("json decode error")
// throw APIError.clientError(message: "client error")
// }
// if responseData.success {
// print(responseData.success)
// return [responseData]
// } else {
// print("실패")
// throw APIError.clientError(message: decodedData.message)
// }
// } else {
// print("Error")
// throw APIError.clientError(message: decodedData.message)
// }
// }
// task.resume()
// }

func postRequest(record: CreateRecord, completionHandler: @escaping (Any) -> Void) {
let url = URL(string: "http://13.125.138.47:8000/record")
print(url)
var request = URLRequest(url: url!)
request.httpMethod = "POST"

Expand All @@ -46,18 +82,18 @@ final class CreateAPIManager: CreateRequestable {
request.addValue("1", forHTTPHeaderField: "userId")

let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in

if let data = data,
let response = response as? HTTPURLResponse,
(200..<500) ~= response.statusCode {
print("response: \(response.statusCode)")
print("response - post: \(response.statusCode)")

guard let responseData = try? JSONDecoder().decode(DreamBaseModel.self, from: data) else {
print("json decode error")
return
}
if responseData.success {
print(responseData.success)
completionHandler(responseData)
} else {
print("실패")
}
Expand Down

0 comments on commit ee6dca9

Please sign in to comment.