Skip to content
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
30 changes: 9 additions & 21 deletions Dietto/Dietto/Domain/Usecases/UserStorageUsecase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ protocol UserStorageUsecase {

func createUserData(_ user: UserEntity) async throws
func getUserData() async throws -> UserEntity
func updateUserDefaultData(id: UUID, name: String, gender: Gender, height: Int) async throws
func updateGoal(id: UUID, weight: Int, distance: Int) async throws
func updateUserDefaultData(id: UUID, userEntity: UserEntity) async throws
func updateCurrentWeight(id: UUID, currentWeight: Int) async throws
func deleteUserData() async throws
}
Expand Down Expand Up @@ -67,28 +66,17 @@ final class UserStorageUsecaseImpl<Repository: AnotherStorageRepository>: UserSt
}
}

func updateUserDefaultData(id: UUID, name: String, gender: Gender, height: Int) async throws {
func updateUserDefaultData(id: UUID, userEntity: UserEntity) async throws {
do {
let predicate = #Predicate<UserDTO> { $0.id == id }
try await storage.updateData(predicate: predicate) { dto in
dto.name = name
dto.gender = gender.rawValue
dto.height = height
}
changeEvent.send()
}
catch {
print(#function, error.localizedDescription)
throw StorageError.updateError
}
}

func updateGoal(id: UUID, weight: Int, distance: Int) async throws {
do {
let predicate = #Predicate<UserDTO> { $0.id == id }
try await storage.updateData(predicate: predicate) { dto in
dto.targetWeight = weight
dto.targetDistance = distance
dto.name = userEntity.name
dto.gender = userEntity.gender.rawValue
dto.height = userEntity.height
// dto.startWeight = userEntity.startWeight
dto.currentWeight = userEntity.currentWeight
dto.targetWeight = userEntity.targetWeight
dto.targetDistance = userEntity.targetDistance
}
changeEvent.send()
}
Expand Down
133 changes: 40 additions & 93 deletions Dietto/Dietto/Presentation/Article/View/ArticleView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,56 +8,51 @@
import SwiftUI

struct ArticleView: View {
let articles = [
"https://www.youtube.com/watch?v=3p8EBPVZ2Iw",
"https://www.news1.kr/articles/?5301234",
"https://www.youtube.com/watch?v=FdYIvEc7e-0",
"https://www.youtube.com/watch?v=2tM1LFFxeKg"
]

@StateObject var viewModel: ArticleViewModel
var body: some View {
ZStack{
Color.backGround.ignoresSafeArea()

NavigationView {
VStack(alignment: .leading){
HStack {
//MARK: - 로고
Text("Dietto")
.font(.NerkoOne40)
.foregroundStyle(.text)
Spacer()

NavigationLink(destination: InterestsView(viewModel: viewModel)) {
Text("관심사 수정")
.font(.pretendardMedium16)
.foregroundColor(.white)
.padding(.vertical, 4)
.padding(.horizontal, 12)
.background(Color.appMain)
.clipShape(Capsule())
}

}
.padding([.leading, .trailing], 16)
Text("내 관심사")
.font(.pretendardBold20)
.padding(.leading, 16)
Interests(
topic: "",
titles: viewModel.selectedInterests.map{$0.title},
onClicked: {_ in },
isSelected: {_ in true}
).padding(.leading, 16)
NavigationView {
VStack(alignment: .leading){
HStack {
//MARK: - 로고
Text("Dietto")
.font(.NerkoOne40)
.foregroundStyle(.text)
Spacer()

List(articles, id: \.self) { item in
LinkRow(previewURL: URL(string: item)!)
.background(Color.backGround).ignoresSafeArea(.all)
NavigationLink(destination: InterestsView(viewModel: viewModel)) {
Text("관심사 수정")
.font(.pretendardMedium16)
.foregroundColor(.white)
.padding(.vertical, 4)
.padding(.horizontal, 12)
.background(Color.appMain)
.clipShape(Capsule())
}
.listStyle(.plain)

}
.padding([.leading, .trailing], 16)
Text("내 관심사")
.font(.pretendardBold20)
.padding(.leading, 16)
Interests(
topic: "",
titles: viewModel.selectedInterests.map{$0.title},
onClicked: {_ in },
isSelected: {_ in true}
).padding(.leading, 16)

List(viewModel.articles, id: \.self) { item in
LinkRow(previewURL: URL(string: item)!)
.background(Color.backGround).ignoresSafeArea(.all)
}
.listStyle(.plain)
.refreshable { viewModel.loadArticles() }
Spacer()
}
.toolbarVisibility(.hidden, for: .navigationBar)
.background(Color.backGround)
.progressOverlay(isPresented: $viewModel.isLoading, message: "아티클 불러오는중..")
.toastView(toast: $viewModel.toastMessage)
}
}
}
Expand All @@ -66,53 +61,5 @@ struct ArticleView: View {
// NavigationView {
// ArticleView(viewModel: ArticleViewModel())
// }
//
//}



//
//
//
/*
[
{
"title": "계룡시, 등굣길 금연 캠페인 성황리에 마무리",
"link": "https://www.news1.kr/articles/?5301234"
},
{
"title": "영도구보건소, 금연구역 인증 걷기 챌린지 운영",
"link": "https://www.news2.kr/articles/?5301235"
},
{
"title": "광주시의회, 세계 금연의 날 맞아 금연 결의 대회 개최",
"link": "https://www.news3.kr/articles/?5301236"
},
{
"title": "팔굽혀펴기로 치매 예방하기?...근육량 증가하면 당뇨·치매 위험 낮아져 [Health Recipe]",
"link": "https://www.healthnews.kr/articles/?5301237"
},
{
"title": "노년층 복병 ‘골근감소증’ “장내 미생물 먹었더니”…뼈밀도·근육량 증가↑",
"link": "https://www.healthnews.kr/articles/?5301238"
},
{
"title": "체중 재증가하는 여성은 근육량보다 지방량 증가가 원인",
"link": "https://www.healthnews.kr/articles/?5301239"
},
{
"title": "금연 무기력함 극복하는 꿀팁 3가지를 소개합니다! : 네이버 블로그",
"link": "https://blog.naver.com/PostView.nhn?blogId=example1&logNo=222123456789"
},
{
"title": "근육량 증가, 근성장을 극대화해줄 꿀팁! - 네이버 블로그",
"link": "https://blog.naver.com/PostView.nhn?blogId=example2&logNo=222123456790"
},
{
"title": "지속 가능한 근육량 증가 운동 프로그램 : 네이버 블로그",
"link": "https://blog.naver.com/PostView.nhn?blogId=example3&logNo=222123456791"
}
]


*/
//}
4 changes: 2 additions & 2 deletions Dietto/Dietto/Presentation/Article/View/LinkRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct LinkRow : UIViewRepresentable {
func makeUIView(context: Context) -> LPLinkView {
let view = LPLinkView(url: previewURL)

let provider = LPMetadataProvider()
let provider = LPMetadataProvider() // Provider Fetch작업을 VM에서 미리하는 방식이 더 좋을거 같음 경고가 엄청뜬다 (nil경고, 주소유효성 경고 등등)
provider.startFetchingMetadata(for: previewURL) { (metadata, error) in
if let md = metadata {
DispatchQueue.main.async {
Expand All @@ -39,4 +39,4 @@ struct LinkRow : UIViewRepresentable {
func updateUIView(_ view: LPLinkView, context: Context) {
// New instance for each update
}
}
}
77 changes: 62 additions & 15 deletions Dietto/Dietto/Presentation/Article/ViewModel/ArticleViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
import SwiftUI

final class ArticleViewModel: ObservableObject {
@Published var toastMessage: ToastEntity?
@Published var selectedInterests: [InterestEntity] = []
@Published var articles: [ArticleEntity] = []
@Published var isLoading : Bool = false
@Published var articles: [String] = []
@Published var isLoading : Bool = true

private let alanUsecase: AlanUsecase
private let storageUsecase: InterestsUsecase
Expand All @@ -22,32 +23,43 @@ final class ArticleViewModel: ObservableObject {
]

init(
alanUsecase: AlanUsecase = AlanUsecaseImpl(repository: NetworkRepositoryImpl()),
storageUsecase: InterestsUsecase /* = InterestsUsecaseImpl(repository: AnotherStorageRepositoryImpl<InterestsDTO>() */
alanUsecase: AlanUsecase,
storageUsecase: InterestsUsecase
) {
self.alanUsecase = alanUsecase
self.storageUsecase = storageUsecase

Task {
do {
let result = try await storageUsecase.fetchInterests()
await MainActor.run { self.selectedInterests = result }
await MainActor.run {
self.selectedInterests = result
loadArticles()
}
}
catch {
#warning("여기에 에러핸들링 토스트 팝업 등 넣기")
await callToastMessage(type: .error, title: "관심사 로드 실패", message: error.localizedDescription)
}
}
}

// MARK: - 아티클 로드
func loadArticles() {
isLoading = true
Task {
do {
let result = try await alanUsecase.fetchArticle(topics: selectedInterests)
await MainActor.run{ articles = result }
// let result = try await alanUsecase.fetchArticle(topics: selectedInterests)
// await MainActor.run{ articles = result }
// MARK: 임시 로직
try await Task.sleep(for: .seconds(5))
await MainActor.run { [weak self] in
self?.articles = Array((self?.dummyData.shuffled().prefix(5))!)
self?.isLoading = false
self?.toastMessage = ToastEntity(type: .success, title: "아티클 업데이트 완료", message: "")
}
}
catch {
#warning("여기에 에러핸들링 토스트 팝업 등 넣기")
await callToastMessage(type: .error, title: "아티클 로드 실패", message: error.localizedDescription)
}
}

Expand All @@ -70,18 +82,53 @@ final class ArticleViewModel: ObservableObject {
if selectedInterests.contains(where: { $0.title == title }) {
removeInterest(title)
Task {
do { try await storageUsecase.deleteInterests(InterestEntity(title: title))}
catch { }
#warning("여기에 에러핸들링 토스트 팝업 등 넣기")
do {
try await storageUsecase.deleteInterests(InterestEntity(title: title))
}
catch {
await callToastMessage(type: .error, title: "관심사 삭제 실패", message: error.localizedDescription)
}
}
} else {
addInterest(title)
Task {
do { try await storageUsecase.insertInterests(InterestEntity(title: title)) }
catch { }
#warning("여기에 에러핸들링 토스트 팝업 등 넣기")
do {
try await storageUsecase.insertInterests(InterestEntity(title: title))
}
catch {
await callToastMessage(type: .error, title: "관심사 추가 실패", message: error.localizedDescription)
}
}

}
}

private func callToastMessage(type: ToastStyle, title: String, message: String) async {
await MainActor.run { [weak self] in
self?.toastMessage = ToastEntity(type: type, title: title, message: message)
}
}

let dummyData = [
"https://www.youtube.com/watch?v=jSuxMiRxnZg",
"https://www.youtube.com/watch?v=2lDheJzSYeo",
"https://www.youtube.com/watch?v=TEHS9dzSTZY",
"https://www.youtube.com/watch?v=MjMkBaqimFo",
"https://www.youtube.com/watch?v=Obu25eMlr4A",
"https://www.youtube.com/watch?v=KFbeFLLJbWo",
"https://www.youtube.com/watch?v=BHY0FxzoKZE",
"https://www.youtube.com/watch?v=8so1WZ4j1oQ",
"https://www.youtube.com/watch?v=zlaZGuXvL04",
"https://www.youtube.com/watch?v=1D9ASR6gSc0",
"https://www.youtube.com/watch?v=Cg_GW7yhq20",
"https://www.youtube.com/watch?v=QWF9mGtjju4",
"https://www.youtube.com/watch?v=YMnIhyWjrb4",
"https://www.youtube.com/watch?v=FoRku07ShZM",
"https://www.youtube.com/watch?v=YNsuneGBsMY",
"https://www.youtube.com/watch?v=3DZqX_2YLiw",
"https://www.youtube.com/watch?v=CSjRBBqfhko",
"https://www.youtube.com/watch?v=wWGulLAa0O0",
"https://www.youtube.com/watch?v=4WV7kAUGrgI",
"https://www.youtube.com/watch?v=8so1WZ4j1oQ"
]
}
2 changes: 1 addition & 1 deletion Dietto/Dietto/Presentation/Common/LogoProgress.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ struct LogoProgressModifier: ViewModifier {
if isPresented {
Rectangle()
.fill(Color.black.opacity(0.3))
.ignoresSafeArea()
// .ignoresSafeArea()

LogoProgress(isAnimated: $isAnimated, message: message)
.onAppear {
Expand Down
Loading