콘텐츠 메인, 콘텐츠 업로드 페이지 추가

This commit is contained in:
Yu Sung
2023-08-11 08:47:10 +09:00
parent 64b0380671
commit a167840162
33 changed files with 2190 additions and 1 deletions

View File

@@ -0,0 +1,88 @@
//
// ContentCreateSelectThemeView.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import SwiftUI
import Kingfisher
struct ContentCreateSelectThemeView: View {
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
@StateObject var viewModel = ContentCreateSelectThemeViewModel()
@Binding var isShowing: Bool
@Binding var selectedTheme: GetAudioContentThemeResponse?
var body: some View {
ZStack {
Color(hex: "222222").ignoresSafeArea()
VStack(spacing: 0) {
HStack(alignment: .top, spacing: 0) {
Text("테마 선택")
.font(.custom(Font.bold.rawValue, size: 18.3))
.foregroundColor(.white)
Spacer()
Image("ic_close_white")
.resizable()
.frame(width: 20, height: 20)
.onTapGesture { isShowing = false }
}
.padding(.horizontal, 26.7)
.padding(.top, 26.7)
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: columns, spacing: 26.7) {
ForEach(viewModel.themes, id: \.self) { theme in
VStack(spacing: 16.7) {
KFImage(URL(string: theme.image))
.resizable()
.scaledToFill()
.frame(width: 60, height: 60, alignment: .top)
.clipShape(Circle())
Text(theme.theme)
.font(.custom(Font.medium.rawValue, size: 14.7))
.foregroundColor(Color(hex: "bbbbbb"))
}
.onTapGesture {
selectedTheme = theme
isShowing = false
}
}
}
}
.padding(.horizontal, 20)
.padding(.top, 26.7)
}
if viewModel.isLoading {
LoadingView()
}
}
.cornerRadius(16.7, corners: [.topLeft, .topRight])
.onAppear {
viewModel.getThemes()
}
}
}
struct ContentCreateSelectThemeView_Previews: PreviewProvider {
static var previews: some View {
ContentCreateSelectThemeView(
isShowing: .constant(true),
selectedTheme: .constant(GetAudioContentThemeResponse(id: 1, theme: "", image: ""))
)
}
}

View File

@@ -0,0 +1,59 @@
//
// ContentCreateSelectThemeViewModel.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import Foundation
import Combine
final class ContentCreateSelectThemeViewModel: ObservableObject {
private let repository = ContentRepository()
private var subscription = Set<AnyCancellable>()
@Published var isLoading = false
@Published var errorMessage = ""
@Published var isShowPopup = false
@Published var themes: [GetAudioContentThemeResponse] = []
func getThemes() {
isLoading = true
repository.getAudioContentThemeList()
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponse<[GetAudioContentThemeResponse]>.self, from: responseData)
if let data = decoded.data, decoded.success {
self.themes.removeAll()
self.themes.append(contentsOf: data)
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
}
self.isShowPopup = true
}
} catch {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
}
}
.store(in: &subscription)
}
}

View File

@@ -0,0 +1,463 @@
//
// ContentCreateView.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import SwiftUI
import Kingfisher
struct ContentCreateView: View {
@StateObject var keyboardHandler = KeyboardHandler()
@StateObject private var viewModel = ContentCreateViewModel()
@State private var isShowPhotoPicker = false
@State private var isShowSelectAudioView = false
@State private var isShowSelectThemeView = false
var body: some View {
BaseView(isLoading: $viewModel.isLoading) {
GeometryReader { proxy in
ZStack {
VStack(spacing: 0) {
DetailNavigationBar(title: "콘텐츠 등록")
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 0) {
Text("썸네일")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
ZStack {
if let selectedImage = viewModel.coverImage {
Image(uiImage: selectedImage)
.resizable()
.scaledToFill()
.frame(width: 107, height: 107)
.background(Color(hex: "3e3358"))
.cornerRadius(8)
.clipped()
} else {
Image("ic_logo")
.resizable()
.scaledToFit()
.padding(13.3)
.frame(width: 107, height: 107)
.background(Color(hex: "3e3358"))
.cornerRadius(8)
}
Image("ic_camera")
.padding(10)
.background(Color(hex: "9970ff"))
.cornerRadius(30)
.offset(x: 50, y: 36)
}
.frame(alignment: .bottomTrailing)
.onTapGesture { isShowPhotoPicker = true }
Text("등록")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 13.3)
Text(viewModel.fileName.trimmingCharacters(in: .whitespacesAndNewlines) == "" ? "파일선택" : viewModel.fileName)
.font(.custom(Font.medium.rawValue, size: 16.7))
.foregroundColor(Color(hex: "9970ff"))
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(Color(hex: "9970ff").opacity(0.2))
.cornerRadius(5.3)
.overlay(
RoundedCorner(radius: 8)
.stroke(lineWidth: 2)
.foregroundColor(Color(hex: "9970ff"))
)
.padding(.top, 13.3)
.onTapGesture { isShowSelectAudioView = true }
}
.padding(.top, 13.3)
.padding(.horizontal, 13.3)
Rectangle()
.foregroundColor(Color(hex: "232323"))
.frame(height: 6.7)
.padding(.top, 26.7)
VStack(spacing: 0) {
Text("제목")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
TextField("제목을 입력하세요", text: $viewModel.title)
.autocapitalization(.none)
.disableAutocorrection(true)
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "eeeeee"))
.padding(.vertical, 16.7)
.padding(.horizontal, 13.3)
.background(Color(hex: "222222"))
.cornerRadius(6.7)
.keyboardType(.default)
.padding(.top, 13.3)
HStack(spacing: 0) {
Text("내용")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
Spacer()
Text("\(viewModel.detail.count)")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "ff5c49")) +
Text(" / 최대 500자")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "777777"))
}
.padding(.top, 26.7)
TextViewWrapper(
text: $viewModel.detail,
placeholder: viewModel.placeholder,
textColorHex: "eeeeee",
backgroundColorHex: "222222"
)
.frame(height: 184)
.cornerRadius(6.7)
.padding(.top, 13.3)
Text("테마")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 26.7)
HStack(spacing: 13.3) {
if let theme = viewModel.theme {
KFImage(URL(string: theme.image))
.resizable()
.frame(width: 33.3, height: 33.3)
.clipShape(Circle())
}
Text(viewModel.theme != nil ?
viewModel.theme!.theme :
"테마 선택")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "9970ff"))
}
.padding(.vertical, viewModel.theme != nil ? 8 : 13.3)
.frame(maxWidth: .infinity)
.background(Color(hex: "9970ff").opacity(0.2))
.cornerRadius(24)
.overlay(
RoundedRectangle(cornerRadius: 24)
.stroke(lineWidth: 2)
.foregroundColor(Color(hex: "9970ff"))
)
.padding(.top, 13.3)
.onTapGesture {
isShowSelectThemeView = true
hideKeyboard()
}
Text("태그")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 26.7)
TextField("예: #연애 #커버곡", text: $viewModel.hashtags)
.autocapitalization(.none)
.disableAutocorrection(true)
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "eeeeee"))
.padding(.vertical, 16.7)
.padding(.horizontal, 13.3)
.background(Color(hex: "222222"))
.cornerRadius(6.7)
.keyboardType(.default)
.padding(.top, 13.3)
}
.padding(.top, 26.7)
.padding(.horizontal, 13.3)
Rectangle()
.foregroundColor(Color(hex: "232323"))
.frame(height: 6.7)
.padding(.top, 26.7)
VStack(spacing: 13.3) {
Text("가격설정")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 13.3) {
SelectButtonView(title: "무료", isChecked: viewModel.isFree) {
if !viewModel.isFree {
viewModel.isFree = true
}
}
SelectButtonView(title: "유료", isChecked: !viewModel.isFree) {
if viewModel.isFree {
viewModel.isFree = false
}
}
}
if !viewModel.isFree {
VStack(spacing: 0) {
Text("소장가격")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "d2d2d2"))
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 0) {
TextField("가격을 입력하세요(10코인 이상)", text: $viewModel.priceString)
.autocapitalization(.none)
.disableAutocorrection(true)
.font(.custom(Font.bold.rawValue, size: 14.7))
.foregroundColor(Color(hex: "eeeeee"))
.cornerRadius(6.7)
.keyboardType(.numberPad)
.padding(.trailing, 10)
Spacer()
Text("코인")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "777777"))
}
.padding(.vertical, 17)
.padding(.horizontal, 13.3)
.background(Color(hex: "222222"))
.cornerRadius(5.3)
.padding(.top, 5.3)
Rectangle()
.foregroundColor(Color(hex: "232323"))
.frame(height: 1)
.padding(.top, 11)
Text("※ 이용기간 대여 (7일) | 소장 (서비스종료시까지)")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "777777"))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 13.3)
Text("※ 대여가격은 소장가격의 70%로 자동 반영")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "777777"))
.frame(maxWidth: .infinity, alignment: .leading)
Text("※ 콘텐츠의 최소금액은 10코인 입니다")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "777777"))
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.top, 26.7)
}
}
.padding(.top, 26.7)
.padding(.horizontal, 13.3)
VStack(spacing: 13.3) {
Text("연령 제한")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 13.3) {
SelectButtonView(title: "전체 연령", isChecked: !viewModel.isAdult) {
if viewModel.isAdult {
viewModel.isAdult = false
}
}
SelectButtonView(title: "19세 이상", isChecked: viewModel.isAdult) {
if !viewModel.isAdult {
viewModel.isAdult = true
}
}
}
Text("성인콘텐츠를 전체관람가로 등록할 시 발생하는 법적 책임은 회사와 상관없이 콘텐츠를 등록한 본인에게 있습니다.\n콘텐츠 내용은 물론 제목도 19금 여부를 체크해 주시기 바랍니다.")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "DD4500"))
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 13.3)
}
.padding(.top, 26.7)
.padding(.horizontal, 13.3)
VStack(spacing: 13.3) {
Text("댓글 가능 여부")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 13.3) {
SelectButtonView(title: "댓글 가능", isChecked: viewModel.isAvailableComment) {
if !viewModel.isAvailableComment {
viewModel.isAvailableComment = true
}
}
SelectButtonView(title: "댓글 불가", isChecked: !viewModel.isAvailableComment) {
if viewModel.isAvailableComment {
viewModel.isAvailableComment = false
}
}
}
}
.padding(.top, 26.7)
.padding(.horizontal, 13.3)
VStack(spacing: 0) {
HStack(alignment: .top, spacing: 0) {
Text("등록")
.font(.custom(Font.bold.rawValue, size: 18.3))
.foregroundColor(Color.white)
.frame(height: 50)
.frame(maxWidth: .infinity)
.background(Color(hex: "9970ff"))
.cornerRadius(10)
.padding(13.3)
}
.frame(maxWidth: .infinity)
.background(Color(hex: "222222"))
.cornerRadius(16.7, corners: [.topLeft, .topRight])
.onTapGesture {
hideKeyboard()
viewModel.uploadAudioContent()
}
Rectangle()
.foregroundColor(Color(hex: "222222"))
.frame(height: keyboardHandler.keyboardHeight)
.frame(maxWidth: .infinity)
if proxy.safeAreaInsets.bottom > 0 {
Rectangle()
.foregroundColor(Color(hex: "222222"))
.frame(height: 15.3)
.frame(maxWidth: .infinity)
}
}
.padding(.top, 30)
}
}
.fileImporter(
isPresented: $isShowSelectAudioView,
allowedContentTypes: [.audio],
allowsMultipleSelection: false
) { result in
switch result {
case .success(let url):
// Handle selected file URL
viewModel.selectedFileUrl = url[0]
case .failure(let error):
// Handle error if needed
print("File import error: \(error.localizedDescription)")
}
}
if isShowPhotoPicker {
ImagePicker(
isShowing: $isShowPhotoPicker,
selectedImage: $viewModel.coverImage,
sourceType: .photoLibrary
)
}
if viewModel.isShowCompletePopup {
SodaDialog(
title: "콘텐츠 업로드",
desc: "등록한 콘텐츠가 업로드 중입니다.\n" +
"콘텐츠 등록이 완료되면 알림을 보내드립니다.\n" +
"이 페이지를 나가도 콘텐츠는 자동으로 등록됩니다.",
confirmButtonTitle: "확인",
confirmButtonAction: { AppState.shared.back() },
cancelButtonTitle: "",
cancelButtonAction: {}
)
}
GeometryReader { proxy in
VStack {
Spacer()
ContentCreateSelectThemeView(
isShowing: $isShowSelectThemeView,
selectedTheme: $viewModel.theme
)
.frame(width: proxy.size.width, height: proxy.size.height * 0.9)
.offset(y: isShowSelectThemeView ? 0 : proxy.size.height * 0.9)
.animation(.easeInOut(duration: 0.49), value: self.isShowSelectThemeView)
}
}
.edgesIgnoringSafeArea(.bottom)
}
.onTapGesture { hideKeyboard() }
.edgesIgnoringSafeArea(.bottom)
.popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
GeometryReader { geo in
HStack {
Spacer()
Text(viewModel.errorMessage)
.padding(.vertical, 13.3)
.frame(width: screenSize().width - 66.7, alignment: .center)
.font(.custom(Font.medium.rawValue, size: 12))
.background(Color(hex: "9970ff"))
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
.cornerRadius(20)
.padding(.top, 66.7)
Spacer()
}
}
}
}
}
}
}
struct SelectButtonView: View {
let title: String
let isChecked: Bool
let action: () -> Void
var body: some View {
HStack(spacing: 6.7) {
if isChecked {
Image("ic_select_check")
}
Text(title)
.font(.custom(Font.bold.rawValue, size: 14.7))
.foregroundColor(isChecked ? .white : Color(hex: "9970ff"))
}
.frame(height: 48.7)
.frame(maxWidth: .infinity)
.background(isChecked ? Color(hex: "9970ff") : Color(hex: "1f1734"))
.cornerRadius(6.7)
.onTapGesture {
hideKeyboard()
action()
}
}
}
struct ContentCreateView_Previews: PreviewProvider {
static var previews: some View {
ContentCreateView()
}
}

View File

@@ -0,0 +1,216 @@
//
// ContentCreateViewModel.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import UIKit
import Moya
import Combine
final class ContentCreateViewModel: ObservableObject {
private let repository = ContentRepository()
private var subscription = Set<AnyCancellable>()
@Published var isLoading = false
@Published var isShowCompletePopup = false
@Published var errorMessage = ""
@Published var isShowPopup = false
@Published var fileName = ""
@Published var title = ""
@Published var detail = ""
@Published var hashtags: String = ""
@Published var theme: GetAudioContentThemeResponse? = nil
@Published var coverImage: UIImage? = nil
@Published var selectedFileUrl: URL? = nil {
didSet {
if let fileUrl = selectedFileUrl {
fileName = fileUrl.lastPathComponent
}
}
}
@Published var isAvailableComment = true
@Published var isAdult = false
@Published var priceString = "0" {
didSet {
if priceString.count > 5 {
priceString = String(priceString.prefix(5))
} else {
if let price = Int(priceString) {
self.price = price
} else {
self.price = 0
}
}
}
}
@Published var price = 0
@Published var isFree = true {
didSet {
if isFree {
priceString = "0"
}
}
}
var placeholder = "내용을 입력하세요"
func uploadAudioContent() {
if !isLoading && validateData() {
isLoading = true
let request = CreateAudioContentRequest(
title: title,
detail: detail,
tags: hashtags,
price: price,
themeId: theme!.id,
isAdult: isAdult,
isCommentAvailable: isAvailableComment
)
var multipartData = [MultipartFormData]()
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
let jsonData = try? encoder.encode(request)
if let jsonData = jsonData {
if let coverImage = coverImage, let imageData = coverImage.jpegData(compressionQuality: 0.8) {
multipartData.append(
MultipartFormData(
provider: .data(imageData),
name: "coverImage",
fileName: "\(UUID().uuidString)_\(Date().timeIntervalSince1970 * 1000).jpg",
mimeType: "image/*")
)
} else {
errorMessage = "커버이미지를 업로드 하지 못했습니다.\n다시 선택해 주세요"
isShowPopup = true
isLoading = false
return
}
if let selectedFileUrl = selectedFileUrl {
if selectedFileUrl.startAccessingSecurityScopedResource() {
defer {
selectedFileUrl.stopAccessingSecurityScopedResource()
}
if let data = try? Data(contentsOf: selectedFileUrl) {
multipartData.append(
MultipartFormData(
provider: .data(data),
name: "contentFile",
fileName: selectedFileUrl.lastPathComponent,
mimeType: "audio/*"
)
)
} else {
errorMessage = "콘텐츠 파일을 업로드 하지 못했습니다.\n다시 선택해 주세요"
isShowPopup = true
isLoading = false
return
}
} else {
errorMessage = "콘텐츠 파일을 업로드 하지 못했습니다.\n다시 선택해 주세요"
isShowPopup = true
isLoading = false
return
}
} else {
errorMessage = "콘텐츠 파일을 업로드 하지 못했습니다.\n다시 선택해 주세요"
isShowPopup = true
isLoading = false
return
}
multipartData.append(MultipartFormData(provider: .data(jsonData), name: "request"))
repository
.uploadAudioContent(parameters: multipartData)
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { [unowned self] response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponseWithoutData.self, from: responseData)
if decoded.success {
self.isShowCompletePopup = true
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
}
self.isShowPopup = true
}
} catch {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
}
}
.store(in: &subscription)
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
self.isLoading = false
}
}
}
private func validateData() -> Bool {
if title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
errorMessage = "제목을 입력해 주세요."
isShowPopup = true
return false
}
if detail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || detail.count < 5 {
errorMessage = "내용을 5자 이상 입력해 주세요."
isShowPopup = true
return false
}
if theme == nil {
errorMessage = "테마를 선택해 주세요."
isShowPopup = true
return false
}
if coverImage == nil {
errorMessage = "커버이미지를 선택해 주세요."
isShowPopup = true
return false
}
if selectedFileUrl == nil {
errorMessage = "오디오 콘텐츠를 선택해 주세요."
isShowPopup = true
return false
}
if !isFree && price < 10 {
errorMessage = "콘텐츠의 최소금액은 10코인 입니다."
isShowPopup = true
return false
}
return true
}
}

View File

@@ -0,0 +1,18 @@
//
// CreateAudioContentRequest.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import Foundation
struct CreateAudioContentRequest: Encodable {
let title: String
let detail: String
let tags: String
let price: Int
let themeId: Int
let isAdult: Bool
let isCommentAvailable: Bool
}

View File

@@ -0,0 +1,14 @@
//
// GetAudioContentThemeResponse.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import Foundation
struct GetAudioContentThemeResponse: Decodable, Hashable {
let id: Int
let theme: String
let image: String
}