From a11498dd658914ba2d1f9ae6d88bc554e08807e1 Mon Sep 17 00:00:00 2001 From: user Date: Wed, 29 Nov 2023 21:31:10 +0800 Subject: [PATCH] v9.0 --- .gitignore | 1 + Podfile | 2 +- README.md | 27 +- WanAndroid_SwiftUI.xcodeproj/project.pbxproj | 8 + .../xcschemes/WanAndroid_SwiftUI.xcscheme | 2 +- .../Content/Home/HomeView.swift | 10 +- .../Content/Home/view/ArticleCellView.swift | 4 +- .../Home/view/ArticleCellViewBuilder.swift | 18 +- .../Home/view/ImageCarouseViewBuilder.swift | 53 +-- .../Home/viewmodel/HomeViewModel.swift | 24 +- .../Content/Me/view/MeBuilder.swift | 9 +- .../component/MessageItemReadBuilder.swift | 19 +- .../component/MessageItemUnReadBuilder.swift | 9 +- .../Message/component/MessageItemView.swift | 2 +- .../Message/view/MessageReadView.swift | 4 +- .../Message/view/MessageUnReadView.swift | 4 +- .../view/NavigationSectionBuilder.swift | 6 +- .../Content/Project/ProjectView.swift | 6 +- .../Content/Project/view/ProjectBuilder.swift | 24 +- .../Project/viewmodel/ProjectViewModel.swift | 8 +- WanAndroid_SwiftUI/api/APIService.swift | 24 +- WanAndroid_SwiftUI/api/Router.swift | 2 +- WanAndroid_SwiftUI/model/ArticleModel.swift | 237 +++++----- WanAndroid_SwiftUI/model/BannerModel.swift | 96 ++-- .../model/CoinUserInfoModel.swift | 96 ++-- .../model/CollectListModel.swift | 160 +++---- WanAndroid_SwiftUI/model/MessageModel.swift | 154 +++--- WanAndroid_SwiftUI/model/ProjectModel.swift | 357 ++------------ .../model/ProjectSonModel.swift | 402 ++-------------- WanAndroid_SwiftUI/model/TreeModel.swift | 447 ++---------------- WanAndroid_SwiftUI/model/UserModel.swift | 346 ++------------ WanAndroid_SwiftUI/utils/Const.swift | 73 +++ 32 files changed, 676 insertions(+), 1958 deletions(-) create mode 100644 WanAndroid_SwiftUI/utils/Const.swift diff --git a/.gitignore b/.gitignore index 581502a..5d53fe0 100644 --- a/.gitignore +++ b/.gitignore @@ -90,3 +90,4 @@ fastlane/test_output iOSInjectionProject/ .DS_Store *.lock +Podfile.lock diff --git a/Podfile b/Podfile index 2523215..595de24 100644 --- a/Podfile +++ b/Podfile @@ -1,5 +1,5 @@ # Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' +platform :ios, '16.0' target 'WanAndroid_SwiftUI' do # Comment the next line if you don't want to use dynamic frameworks diff --git a/README.md b/README.md index 46200fc..57033fa 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,11 @@ ViewModel(MVVM设计模式): * 通过onReceive方法,监听标签的切换,显示相应的视图 +### v9.0 + +* 数据实体类(bean)由quicktype.io生成改为AlamofireObjectMapper +* 解决能够接收到数据,页面无法显示问题 + ## 四 开发任务 ### 4.1 已完成 @@ -174,14 +179,14 @@ ViewModel(MVVM设计模式): * swiftUI练手项目,可能存在代码不规范等错误,如有错误还望指正 -[swift-waz-1]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-home-1.png -[swift-waz-2]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-detail-2.png -[swift-waz-3]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-navigator-3.png -[swift-waz-4]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-project-4.png -[swift-waz-5]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-message-unread-5.png -[swift-waz-6]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-message-read-6.png -[swift-waz-7]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-message-info-7.png -[swift-waz-8]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-me-info-8.png -[swift-waz-9]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-me-info-no-9.png -[swift-waz-10]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-login-10.png -[swift-waz-11]:https://cdn.staticaly.com/gh/PGzxc/CDN/master/blog-resume/swiftui-waz-register-11.png +[swift-waz-1]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-home-1.png +[swift-waz-2]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-detail-2.png +[swift-waz-3]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-navigator-3.png +[swift-waz-4]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-project-4.png +[swift-waz-5]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-message-unread-5.png +[swift-waz-6]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-message-read-6.png +[swift-waz-7]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-message-info-7.png +[swift-waz-8]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-me-info-8.png +[swift-waz-9]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-me-info-no-9.png +[swift-waz-10]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-login-10.png +[swift-waz-11]:https://jsd.onmicrosoft.cn/gh/PGzxc/CDN/blog-resume/swiftui-waz-register-11.png diff --git a/WanAndroid_SwiftUI.xcodeproj/project.pbxproj b/WanAndroid_SwiftUI.xcodeproj/project.pbxproj index 06e770f..aac75c7 100644 --- a/WanAndroid_SwiftUI.xcodeproj/project.pbxproj +++ b/WanAndroid_SwiftUI.xcodeproj/project.pbxproj @@ -31,6 +31,7 @@ F3BDCCE82A37094D00FC3CCD /* Router.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3BDCCE72A37094D00FC3CCD /* Router.swift */; }; F3BDCCEA2A37096900FC3CCD /* APIService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3BDCCE92A37096900FC3CCD /* APIService.swift */; }; F3BDCCED2A370A0800FC3CCD /* HomeViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3BDCCEC2A370A0800FC3CCD /* HomeViewModel.swift */; }; + F3CBED4F2B1701BE00D7E722 /* Const.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3CBED4E2B1701BE00D7E722 /* Const.swift */; }; F3D56EA22A36CC4D008876F0 /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3D56E972A36CC4D008876F0 /* HomeView.swift */; }; F3D56EA32A36CC4D008876F0 /* NavigationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3D56E992A36CC4D008876F0 /* NavigationView.swift */; }; F3D56EA42A36CC4D008876F0 /* TabBarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3D56E9B2A36CC4D008876F0 /* TabBarView.swift */; }; @@ -86,6 +87,7 @@ F3BDCCE72A37094D00FC3CCD /* Router.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Router.swift; sourceTree = ""; }; F3BDCCE92A37096900FC3CCD /* APIService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIService.swift; sourceTree = ""; }; F3BDCCEC2A370A0800FC3CCD /* HomeViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeViewModel.swift; sourceTree = ""; }; + F3CBED4E2B1701BE00D7E722 /* Const.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Const.swift; sourceTree = ""; }; F3D56E972A36CC4D008876F0 /* HomeView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = ""; }; F3D56E992A36CC4D008876F0 /* NavigationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavigationView.swift; sourceTree = ""; }; F3D56E9B2A36CC4D008876F0 /* TabBarView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TabBarView.swift; sourceTree = ""; }; @@ -223,6 +225,7 @@ isa = PBXGroup; children = ( F3BDCCD52A3705B400FC3CCD /* Storage.swift */, + F3CBED4E2B1701BE00D7E722 /* Const.swift */, ); path = utils; sourceTree = ""; @@ -571,6 +574,7 @@ F3BDCCEA2A37096900FC3CCD /* APIService.swift in Sources */, F3DA090B2A419EC30089A7A6 /* CoinUserInfoModel.swift in Sources */, F3D5EE1A2A3C6A64000ACDFF /* NavigationSectionBuilder.swift in Sources */, + F3CBED4F2B1701BE00D7E722 /* Const.swift in Sources */, F3BDCCE62A37092F00FC3CCD /* API.swift in Sources */, F3BDCCE82A37094D00FC3CCD /* Router.swift in Sources */, F3D6F7F12A57A44100D9801E /* SwiftUIView.swift in Sources */, @@ -645,6 +649,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp = YES; IPHONEOS_DEPLOYMENT_TARGET = 16.4; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -699,6 +704,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp = YES; IPHONEOS_DEPLOYMENT_TARGET = 16.4; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; @@ -718,6 +724,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_ASSET_PATHS = "\"WanAndroid_SwiftUI/Preview Content\""; + DEVELOPMENT_TEAM = 34LPAHZG4A; ENABLE_PREVIEWS = YES; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; @@ -748,6 +755,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_ASSET_PATHS = "\"WanAndroid_SwiftUI/Preview Content\""; + DEVELOPMENT_TEAM = 34LPAHZG4A; ENABLE_PREVIEWS = YES; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; diff --git a/WanAndroid_SwiftUI.xcodeproj/xcshareddata/xcschemes/WanAndroid_SwiftUI.xcscheme b/WanAndroid_SwiftUI.xcodeproj/xcshareddata/xcschemes/WanAndroid_SwiftUI.xcscheme index 4a67e8c..a23da84 100644 --- a/WanAndroid_SwiftUI.xcodeproj/xcshareddata/xcschemes/WanAndroid_SwiftUI.xcscheme +++ b/WanAndroid_SwiftUI.xcodeproj/xcshareddata/xcschemes/WanAndroid_SwiftUI.xcscheme @@ -1,6 +1,6 @@ 0){ ForEach(messages!){ messages in MessageItemView(message:.constant(messages)) } + }else { + VStack(alignment: .center){ + Button("暂时没有数据哦,点击刷新"){ + vm.getMessageRead(page: 1) + } + } + .frame(width: UIScreen.main.bounds.width,height:UIScreen.main.bounds.height) } + }.onAppear(){ + vm.getMessageRead(page: 1) } } } struct MessageItemBuilder_Previews: PreviewProvider { static var previews: some View { - let vm: MessageReadViewModel = MessageReadViewModel() - MessageItemReadBuilder(vm: .constant(vm)) + let vm: MessageReadViewModel = MessageReadViewModel() + MessageItemReadBuilder(vm:vm) } } diff --git a/WanAndroid_SwiftUI/Content/Message/component/MessageItemUnReadBuilder.swift b/WanAndroid_SwiftUI/Content/Message/component/MessageItemUnReadBuilder.swift index e1df871..039488e 100644 --- a/WanAndroid_SwiftUI/Content/Message/component/MessageItemUnReadBuilder.swift +++ b/WanAndroid_SwiftUI/Content/Message/component/MessageItemUnReadBuilder.swift @@ -8,10 +8,11 @@ import SwiftUI struct MessageItemUnReadBuilder: View { - @Binding var vm: MessageUnReadViewModel + @StateObject var vm: MessageUnReadViewModel = MessageUnReadViewModel() var body: some View { VStack{ let messages = vm.messageModel?.data?.datas + //let messages = Const.shared.getMessageModel().data?.datas if(messages != nil && messages!.count > 0){ ForEach(messages!){ messages in MessageItemView(message:.constant(messages)) @@ -22,8 +23,10 @@ struct MessageItemUnReadBuilder: View { vm.getMessageUnRead(page: 1) } } - .frame(width: UIScreen.main.bounds.width,height: UIScreen.main.bounds.height) + .frame(width: UIScreen.main.bounds.width,height:UIScreen.main.bounds.height) } + }.onAppear(){ + vm.getMessageUnRead(page: 1) } } } @@ -31,6 +34,6 @@ struct MessageItemUnReadBuilder: View { struct MessageItemUnReadBuilder_Previews: PreviewProvider { static var previews: some View { let vm: MessageUnReadViewModel = MessageUnReadViewModel() - MessageItemUnReadBuilder(vm: .constant(vm)) + MessageItemUnReadBuilder(vm: vm) } } diff --git a/WanAndroid_SwiftUI/Content/Message/component/MessageItemView.swift b/WanAndroid_SwiftUI/Content/Message/component/MessageItemView.swift index addfeac..f5c707d 100644 --- a/WanAndroid_SwiftUI/Content/Message/component/MessageItemView.swift +++ b/WanAndroid_SwiftUI/Content/Message/component/MessageItemView.swift @@ -64,6 +64,6 @@ struct MessageItemView: View { } struct MessageItemView_Previews: PreviewProvider { static var previews: some View { - MessageItemView(message: .constant(Message(category: 2, date: 1687162598000, fromUser: "yndongyong", fromUserID: 63839, fullLink: "https://wanandroid.com/wenda/show/8857", id: 747349, isRead: 1, link: "/wenda/show/8857", message: "奔溃异常的每一行最后为什么会带有TbsSdk.java的字眼,只集成了Sentry这一类奔溃捕获框架,google了TbsSdk也没有搜索出结果,只搜索到腾讯tbs服务,但是没有继承这一框架。通过./gradlew app:dependencies --scan --configuration normalDebugRuntimeClasspath 分析了第三方依赖...", niceDate: "1天前", tag: "新回答", title: "回答了:每日一问 问答征集", userID: 26707))) + MessageItemView(message: .constant(Const.shared.getMessage())) } } diff --git a/WanAndroid_SwiftUI/Content/Message/view/MessageReadView.swift b/WanAndroid_SwiftUI/Content/Message/view/MessageReadView.swift index 806aa15..9822218 100644 --- a/WanAndroid_SwiftUI/Content/Message/view/MessageReadView.swift +++ b/WanAndroid_SwiftUI/Content/Message/view/MessageReadView.swift @@ -12,9 +12,7 @@ struct MessageReadView: View { @StateObject private var vm: MessageReadViewModel = MessageReadViewModel() var body: some View { - MessageItemReadBuilder(vm: .constant(vm)).onAppear(){ - vm.getMessageRead(page: 1) - } + MessageItemReadBuilder() } } diff --git a/WanAndroid_SwiftUI/Content/Message/view/MessageUnReadView.swift b/WanAndroid_SwiftUI/Content/Message/view/MessageUnReadView.swift index 3ba0b6e..f0e3654 100644 --- a/WanAndroid_SwiftUI/Content/Message/view/MessageUnReadView.swift +++ b/WanAndroid_SwiftUI/Content/Message/view/MessageUnReadView.swift @@ -11,9 +11,7 @@ struct MessageUnReadView: View { @StateObject private var vm: MessageUnReadViewModel = MessageUnReadViewModel() var body: some View { - MessageItemUnReadBuilder(vm: .constant(vm)).onAppear(){ - vm.getMessageUnRead(page: 1) - } + MessageItemUnReadBuilder() } } diff --git a/WanAndroid_SwiftUI/Content/Navigation/view/NavigationSectionBuilder.swift b/WanAndroid_SwiftUI/Content/Navigation/view/NavigationSectionBuilder.swift index 3f8082f..61db9c8 100644 --- a/WanAndroid_SwiftUI/Content/Navigation/view/NavigationSectionBuilder.swift +++ b/WanAndroid_SwiftUI/Content/Navigation/view/NavigationSectionBuilder.swift @@ -19,11 +19,11 @@ struct NavigationSectionBuilder: View { if(treeDatas != nil ){ ForEach(treeDatas!){ treeItem in - Section(header: Text(treeItem.name).font(Font.system(size: 18))) { + Section(header: Text(treeItem.name!).font(Font.system(size: 18))) { //标签 LazyVGrid(columns: columns, spacing: 10){ - ForEach(treeItem.children){ treeItem in - Button(treeItem.name) {} + ForEach(treeItem.children!){ treeItem in + Button(treeItem.name!) {} .padding(EdgeInsets(top: 5, leading: 8, bottom: 5, trailing: 8)) .border(.gray,width: 1) .cornerRadius(2) diff --git a/WanAndroid_SwiftUI/Content/Project/ProjectView.swift b/WanAndroid_SwiftUI/Content/Project/ProjectView.swift index d56e92f..d8feea9 100644 --- a/WanAndroid_SwiftUI/Content/Project/ProjectView.swift +++ b/WanAndroid_SwiftUI/Content/Project/ProjectView.swift @@ -8,14 +8,12 @@ import SwiftUI struct ProjectView: View { - @StateObject private var vm: ProjectViewModel = ProjectViewModel() + //@StateObject private var vm: ProjectViewModel = ProjectViewModel() var body: some View { //SwiftUIView() // ProjectBuilder(vm: .constant(vm)).pickView //ProjectBuilder(vm: .constant(vm)).articleView - ProjectBuilder(vm: .constant(vm)).onAppear(){ - vm.getProjectModel() - } + ProjectBuilder() } } diff --git a/WanAndroid_SwiftUI/Content/Project/view/ProjectBuilder.swift b/WanAndroid_SwiftUI/Content/Project/view/ProjectBuilder.swift index 7065a2f..de62215 100644 --- a/WanAndroid_SwiftUI/Content/Project/view/ProjectBuilder.swift +++ b/WanAndroid_SwiftUI/Content/Project/view/ProjectBuilder.swift @@ -9,7 +9,7 @@ import SwiftUI struct ProjectBuilder: View { - @Binding var vm: ProjectViewModel + @StateObject var vm: ProjectViewModel = ProjectViewModel() @State var selectedOptionIndex = 0 @@ -24,14 +24,13 @@ struct ProjectBuilder: View { articleView } + }.onAppear(){ + vm.getProjectModel() } } var pickView: some View{ ScrollView(.horizontal){ -// if vm.options.isEmpty{ -// Text("Loading") -// }else { HStack(spacing: 0){ Picker("Options",selection: $selectedOptionIndex){ @@ -45,7 +44,7 @@ struct ProjectBuilder: View { }.onReceive([self.selectedOptionIndex].publisher.first()) { value in // 当选择值发生变化时执行操作 if(!vm.options.isEmpty ){ - var option = vm.options[value] + let option = vm.options[value] vm.getProjectTreeArticle(page: 1, cid: vm.optionsDic[option] ?? 0) print("Selected option: \(value)") } @@ -67,20 +66,7 @@ struct ProjectBuilder: View { } } } - } - - // ScrollView{ - // ForEach(vm.options,id: \.self) { option in - // let articleList = vm.projectDictionArticleDataList[vm.optionsDic[option]!] - // if(articleList != nil){ - // ForEach(articleList!){ article in - // ArticleCellView(article: .constant(article)) - // } - // } - // } - // } - } } @@ -89,6 +75,6 @@ struct ProjectBuilderView_Previews: PreviewProvider { static var previews: some View { let vm: ProjectViewModel = ProjectViewModel() - ProjectBuilder(vm: .constant(vm)) + ProjectBuilder(vm:vm) } } diff --git a/WanAndroid_SwiftUI/Content/Project/viewmodel/ProjectViewModel.swift b/WanAndroid_SwiftUI/Content/Project/viewmodel/ProjectViewModel.swift index a1ae0c0..25032f5 100644 --- a/WanAndroid_SwiftUI/Content/Project/viewmodel/ProjectViewModel.swift +++ b/WanAndroid_SwiftUI/Content/Project/viewmodel/ProjectViewModel.swift @@ -31,9 +31,9 @@ class ProjectViewModel:ObservableObject{ debugPrint(error) return } - projectModel?.data.forEach({ project in - self.options.append(project.name) - self.optionsDic.updateValue(project.id, forKey: project.name) + projectModel?.data!.forEach({ project in + self.options.append(project.name!) + self.optionsDic.updateValue(project.id!, forKey: project.name!) }) self.options_first = self.options.first ?? "" self.projectModel = projectModel @@ -49,7 +49,7 @@ class ProjectViewModel:ObservableObject{ } self.projectSonModel = projectSonModel - self.projectDictionArticleDataList.updateValue(projectSonModel!.data.datas, forKey: cid) + self.projectDictionArticleDataList.updateValue(projectSonModel!.data!.datas!, forKey: cid) //self.projectSonModelDataList.append(projectSonModel!.data) }) diff --git a/WanAndroid_SwiftUI/api/APIService.swift b/WanAndroid_SwiftUI/api/APIService.swift index 1cf7309..1802b29 100644 --- a/WanAndroid_SwiftUI/api/APIService.swift +++ b/WanAndroid_SwiftUI/api/APIService.swift @@ -7,6 +7,7 @@ import Foundation import Alamofire +import AlamofireObjectMapper struct APIService { @@ -14,12 +15,13 @@ struct APIService { //MARK: - Singleton static let instance = APIService() - init(){} + private init(){} //MARK: - URL func getBanner(completion:@escaping (BannerModel?, Error?)->()){ - Alamofire.request(Router.homeBanner).responseBannerModel{(response: DataResponse) in + + Alamofire.request(Router.homeBanner).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) return @@ -33,7 +35,7 @@ struct APIService { func getArticle(with page: Int,completion:@escaping (ArticleModel?, Error?)->()){ - Alamofire.request(Router.homeArticleList(page)).responseArticleModel{(response: DataResponse) in + Alamofire.request(Router.homeArticleList(page)).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) @@ -48,7 +50,7 @@ struct APIService { func userLogin(with username:String,with password:String,completion:@escaping (UserModel?, Error?)->()){ - Alamofire.request(Router.login(username, password)).responseUserModel{ (response:DataResponse) in + Alamofire.request(Router.login(username, password)).responseObject{ (response:DataResponse) in if let error = response.error{ completion(nil,error) @@ -67,7 +69,7 @@ struct APIService { func getCollectList(with index: Int,completion:@escaping (CollectListModel?, Error?)->()){ - Alamofire.request(Router.collectList(index)).responseCollectListModel{(response:DataResponse) in + Alamofire.request(Router.collectList(index)).responseObject{(response:DataResponse) in if let error = response.error{ completion(nil,error) @@ -82,7 +84,7 @@ struct APIService { //体系 func getTree(completion:@escaping (TreeModel?, Error?)->()){ - Alamofire.request(Router.tree).responseTreeModel{(response: DataResponse) in + Alamofire.request(Router.tree).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) return @@ -95,7 +97,7 @@ struct APIService { } //项目 func getProject(completion:@escaping (ProjectModel?, Error?)->()){ - Alamofire.request(Router.project).responseProjectModel{(response: DataResponse) in + Alamofire.request(Router.project).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) return @@ -108,7 +110,7 @@ struct APIService { } //项目-子-文章 func getProjectArticle(with page: Int, andWith cid:Int,completion:@escaping (ProjectSonModel?, Error?)->()){ - Alamofire.request(Router.projectArticle(page, cid)).responseProjectSonModel{(response: DataResponse) in + Alamofire.request(Router.projectArticle(page, cid)).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) return @@ -121,7 +123,7 @@ struct APIService { } //用户信息 func getCoinUserInfo(completion:@escaping (CoinUserInfoModel?, Error?)->()){ - Alamofire.request(Router.coinUserInfo).responseCoinUserInfoModel{(response: DataResponse) in + Alamofire.request(Router.coinUserInfo).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) return @@ -135,7 +137,7 @@ struct APIService { //消息-未读 func getMessageUnRead(with page: Int,completion:@escaping (MessageModel?, Error?)->()){ - Alamofire.request(Router.messageUnRead(page)).responseMessageModel{(response: DataResponse) in + Alamofire.request(Router.messageUnRead(page)).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) @@ -151,7 +153,7 @@ struct APIService { //消息-已读 func getMessageRead(with page: Int,completion:@escaping (MessageModel?, Error?)->()){ - Alamofire.request(Router.messageRead(page)).responseMessageModel{(response: DataResponse) in + Alamofire.request(Router.messageRead(page)).responseObject{(response: DataResponse) in if let error = response.error{ completion(nil,error) diff --git a/WanAndroid_SwiftUI/api/Router.swift b/WanAndroid_SwiftUI/api/Router.swift index 6a69ba5..6871dfd 100644 --- a/WanAndroid_SwiftUI/api/Router.swift +++ b/WanAndroid_SwiftUI/api/Router.swift @@ -89,7 +89,7 @@ internal extension APIService{ let encoding = URLEncoding.default return try encoding.encode(request, with: params) - return request + //return request } } } diff --git a/WanAndroid_SwiftUI/model/ArticleModel.swift b/WanAndroid_SwiftUI/model/ArticleModel.swift index 7f37437..0519091 100644 --- a/WanAndroid_SwiftUI/model/ArticleModel.swift +++ b/WanAndroid_SwiftUI/model/ArticleModel.swift @@ -7,147 +7,132 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - ArticleModel -struct ArticleModel: Codable,ModelProtocol { +class ArticleModel: Mappable{ - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder - } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + var data: ArticleModelData? + var errorCode: Int? + var errorMsg: String? + required init?(map:Map) { + } - let data: ArticleModelData? - let errorCode: Int? - let errorMsg: String? + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] + } } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseArticleModelData { response in -// if let articleModelData = response.result.value { -// ... -// } -// } - // MARK: - ArticleModelData -struct ArticleModelData: Codable { - let curPage: Int? - let datas: [Article]? - let offset: Int? - let over: Bool? - let pageCount, size, total: Int? +class ArticleModelData: Mappable{ + var curPage: Int? + var datas: [Article]? = [] + var offset: Int? + var over: Bool? + var pageCount, size, total: Int? + + required init?(map:Map) { + + } + func mapping(map: Map) { + curPage <- map["curPage"] + datas <- map["datas"] + offset <- map["offset"] + over <- map["over"] + pageCount <- map["pageCount"] + size <- map["size"] + total <- map["total"] + } } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDataElement { response in -// if let dataElement = response.result.value { -// ... -// } -// } - // MARK: - DataElement -struct Article: Codable,Identifiable,Equatable { - let adminAdd: Bool? - let apkLink: String? - let audit: Int? - let author: String? - let canEdit: Bool? - let chapterID: Int? - let chapterName: String? - let collect: Bool? - let courseID: Int? - let descMd: String? - let envelopePic: String? - let fresh: Bool? - let host: String? - let id: Int? - let isAdminAdd: Bool? - let link: String? - let desc,niceDate, niceShareDate, origin, dataPrefix: String? - let projectLink: String? - let publishTime, realSuperChapterID, selfVisible, shareDate: Int? - let shareUser: String? - let superChapterID: Int? - let superChapterName: String? - let tags: [Tag]? - let title: String? - let type, userID, visible, zan: Int? - - enum CodingKeys: String, CodingKey { - case adminAdd, apkLink, audit, author, canEdit - case chapterID = "chapterId" - case chapterName, collect - case courseID = "courseId" - case desc, descMd, envelopePic, fresh, host, id, isAdminAdd, link, niceDate, niceShareDate, origin - case dataPrefix = "prefix" - case projectLink, publishTime - case realSuperChapterID = "realSuperChapterId" - case selfVisible, shareDate, shareUser - case superChapterID = "superChapterId" - case superChapterName, tags, title, type - case userID = "userId" - case visible, zan +class Article: Mappable,Identifiable { + + var adminAdd: Bool? + var apkLink: String? + var audit: Int? + var author: String? + var canEdit: Bool? + var chapterId: Int? + var chapterName: String? + var collect: Bool? + var courseId: Int? + var descMd: String? + var envelopePic: String? + var fresh: Bool? + var host: String? + var id: Int? + var isAdminAdd: Bool? + var link: String? + var desc,niceDate, niceShareDate, origin, prefix: String? + var projectLink: String? + var publishTime, realSuperChapterId, selfVisible, shareDate: Int? + var shareUser: String? + var superChapterId: Int? + var superChapterName: String? + var tags: [Tag]? + var title: String? + var type, userId, visible, zan: Int? + + init() { + } + + required init?(map:ObjectMapper.Map) { + } - static func ==(lhs: Article, rhs: Article) -> Bool { - return lhs.id == rhs.id + func mapping(map: ObjectMapper.Map) { + adminAdd <- map["adminAdd"] + apkLink <- map["apkLink"] + audit <- map["audit"] + author <- map["author"] + canEdit <- map["canEdit"] + chapterId <- map["chapterId"] + chapterName <- map["chapterName"] + collect <- map["collect"] + courseId <- map["courseId"] + descMd <- map["descMd"] + envelopePic <- map["envelopePic"] + fresh <- map["fresh"] + host <- map["host"] + id <- map["id"] + isAdminAdd <- map["isAdminAdd"] + link <- map["link"] + desc <- map["desc"] + niceDate <- map["niceDate"] + niceShareDate <- map["niceShareDate"] + origin <- map["origin"] + prefix <- map["prefix"] + projectLink <- map["dataPrefix"] + publishTime <- map["publishTime"] + realSuperChapterId <- map["realSuperChapterId"] + selfVisible <- map["selfVisible"] + shareDate <- map["shareDate"] + shareUser <- map["shareUser"] + superChapterId <- map["superChapterId"] + superChapterName <- map["superChapterName"] + tags <- map["tags"] + title <- map["title"] + type <- map["type"] + userId <- map["userId"] + visible <- map["visible"] + zan <- map["zan"] + } + } - -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseTag { response in -// if let tag = response.result.value { -// ... -// } -// } - // MARK: - Tag -struct Tag: Codable { - let name, url: String? -} - -// MARK: - Helper functions for creating encoders and decoders - - - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) +class Tag:Mappable,Identifiable{ + var name:String? + var url: String? + + required init?(map:Map) { + } - - @discardableResult - func responseArticleModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) + func mapping(map: Map) { + name <- map["name"] + url <- map["url"] } } - diff --git a/WanAndroid_SwiftUI/model/BannerModel.swift b/WanAndroid_SwiftUI/model/BannerModel.swift index faca314..5121be2 100644 --- a/WanAndroid_SwiftUI/model/BannerModel.swift +++ b/WanAndroid_SwiftUI/model/BannerModel.swift @@ -7,77 +7,47 @@ import Foundation import Alamofire +import ObjectMapper // //// MARK: - BannerModel -struct BannerModel: Codable ,ModelProtocol{ +class BannerModel: Mappable,ObservableObject{ - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder + var data: [Banner]? + var errorCode: Int? + var errorMsg: String? + + required init?(map:Map) { + } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - - let data: [Banner]? - let errorCode: Int - let errorMsg: String } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDatum { response in -// if let datum = response.result.value { -// ... -// } -// } - // MARK: - Datum -struct Banner: Codable,Identifiable,Equatable { - let desc: String - let id: Int - let imagePath: String - let isVisible, order: Int - let title: String - let type: Int - let url: String -} - -// MARK: - Helper functions for creating encoders and decoders - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) +class Banner: Mappable,Identifiable, ObservableObject { + + var desc: String? + var id: Int? + var imagePath: String? + var isVisible, order: Int? + var title: String? + var type: Int? + var url: String? + + required init?(map:Map) { + } - - @discardableResult - func responseBannerModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) + func mapping(map:Map) { + desc <- map["desc"] + id <- map["id"] + imagePath <- map["imagePath"] + isVisible <- map["isVisible"] + order <- map["order"] + title <- map["title"] + type <- map["type"] + url <- map["url"] } } - - diff --git a/WanAndroid_SwiftUI/model/CoinUserInfoModel.swift b/WanAndroid_SwiftUI/model/CoinUserInfoModel.swift index a8fae6d..e7ddce8 100644 --- a/WanAndroid_SwiftUI/model/CoinUserInfoModel.swift +++ b/WanAndroid_SwiftUI/model/CoinUserInfoModel.swift @@ -21,80 +21,44 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - UserInfoModel -struct CoinUserInfoModel: Codable ,ModelProtocol { - // MARK: - Helper functions for creating encoders and decoders - - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder +class CoinUserInfoModel: Mappable { + + var data: UserInfo? + var errorCode: Int? + var errorMsg: String? + + required init?(map:Map) { + } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - - let data: UserInfo? - let errorCode: Int? - let errorMsg: String? } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDataClass { response in -// if let dataClass = response.result.value { -// ... -// } -// } // MARK: - DataClass -struct UserInfo: Codable { - let coinCount, level: Int? - let nickname, rank: String? - let userID: Int? - let username: String? - - enum CodingKeys: String, CodingKey { - case coinCount, level, nickname, rank - case userID = "userId" - case username - } -} - - - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) +class UserInfo: Mappable { + var coinCount, level: Int? + var nickname, rank: String? + var userID: Int? + var username: String? + + + required init?(map:Map) { + } - - @discardableResult - func responseCoinUserInfoModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) + func mapping(map: Map) { + coinCount <- map["coinCount"] + level <- map["level"] + nickname <- map["nickname"] + rank <- map["rank"] + userID <- map["userID"] + username <- map["username"] } + } - diff --git a/WanAndroid_SwiftUI/model/CollectListModel.swift b/WanAndroid_SwiftUI/model/CollectListModel.swift index 1a77a2d..7261f8b 100644 --- a/WanAndroid_SwiftUI/model/CollectListModel.swift +++ b/WanAndroid_SwiftUI/model/CollectListModel.swift @@ -21,113 +21,83 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - CollectListModel -struct CollectListModel: Codable ,ModelProtocol{ +class CollectListModel: Mappable{ - // MARK: - Helper functions for creating encoders and decoders - - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder + var data: CollectListModelData? + var errorCode: Int? + var errorMsg: String? + + required init?(map:Map) { + } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - - let data: CollectListModelData? - let errorCode: Int? - let errorMsg: String? } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseCollectListModelData { response in -// if let collectListModelData = response.result.value { -// ... -// } -// } - // MARK: - CollectListModelData -struct CollectListModelData: Codable { - let curPage: Int? - let datas: [CollectModel]? - let offset: Int? - let over: Bool? - let pageCount, size, total: Int? -} - -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDataElement { response in -// if let dataElement = response.result.value { -// ... -// } -// } - -// MARK: - DataElement -struct CollectModel: Codable { - let author: String? - let chapterID: Int? - let chapterName: String? - let courseID: Int? - let desc: String? - let envelopePic: String? - let id: Int? - let link: String? - let niceDate, origin: String? - let originID, publishTime: Int? - let title: String? - let userID, visible, zan: Int? - - enum CodingKeys: String, CodingKey { - case author - case chapterID = "chapterId" - case chapterName - case courseID = "courseId" - case desc, envelopePic, id, link, niceDate, origin - case originID = "originId" - case publishTime, title - case userID = "userId" - case visible, zan +class CollectListModelData: Mappable { + var curPage: Int? + var datas: [CollectModel]? + var offset: Int? + var over: Bool? + var pageCount, size, total: Int? + + required init?(map:Map) { + + } + func mapping(map: Map) { + curPage <- map["curPage"] + datas <- map["datas"] + offset <- map["offset"] + over <- map["over"] + pageCount <- map["pageCount"] + size <- map["size"] + total <- map["total"] } } - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) +// MARK: - DataElement +class CollectModel: Mappable { + var author: String? + var chapterID: Int? + var chapterName: String? + var courseID: Int? + var desc: String? + var envelopePic: String? + var id: Int? + var link: String? + var niceDate, origin: String? + var originID, publishTime: Int? + var title: String? + var userID, visible, zan: Int? + + required init?(map:Map) { + } - - @discardableResult - func responseCollectListModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) + func mapping(map: Map) { + author <- map["author"] + chapterID <- map["chapterID"] + chapterName <- map["chapterName"] + courseID <- map["courseID"] + desc <- map["desc"] + envelopePic <- map["envelopePic"] + id <- map["id"] + link <- map["link"] + niceDate <- map["niceDate"] + origin <- map["origin"] + originID <- map["originID"] + publishTime <- map["publishTime"] + title <- map["title"] + userID <- map["userID"] + visible <- map["visible"] + zan <- map["zan"] } + } - diff --git a/WanAndroid_SwiftUI/model/MessageModel.swift b/WanAndroid_SwiftUI/model/MessageModel.swift index 2cc47e3..47b1c01 100644 --- a/WanAndroid_SwiftUI/model/MessageModel.swift +++ b/WanAndroid_SwiftUI/model/MessageModel.swift @@ -21,111 +21,79 @@ import Foundation import Alamofire - +import ObjectMapper // MARK: - MessageModel -struct MessageModel: Codable { +class MessageModel: Mappable { - let data: MessageModelData? - let errorCode: Int? - let errorMsg: String? + var data: MessageModelData? + var errorCode: Int? + var errorMsg: String? + + + required init?(map:Map) { + + } + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] + } } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseMessageModelData { response in -// if let messageModelData = response.result.value { -// ... -// } -// } - // MARK: - MessageModelData -struct MessageModelData: Codable { - - let curPage: Int? - let datas: [Message]? - let offset: Int? - let over: Bool? - let pageCount, size, total: Int? -} - -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDataElement { response in -// if let dataElement = response.result.value { -// ... -// } -// } +class MessageModelData: Mappable { -// MARK: - DataElement -struct Message: Codable,Identifiable,Equatable { + var curPage: Int? + var datas: [Message]? + var offset: Int? + var over: Bool? + var pageCount, size, total: Int? - let category, date: Int? - let fromUser: String? - let fromUserID: Int? - let fullLink: String? - let id, isRead: Int? - let link: String? - let message, niceDate: String? - let tag: String? - let title: String? - let userID: Int? - - enum CodingKeys: String, CodingKey { - case category, date, fromUser - case fromUserID = "fromUserId" - case fullLink, id, isRead, link, message, niceDate, tag, title - case userID = "userId" + required init?(map:Map) { + } -} - -//enum Link: String, Codable { -// case wendaShow8857 = "/wenda/show/8857" -//} - - -// MARK: - Helper functions for creating encoders and decoders -//func newJSONDecoder() -> JSONDecoder { -// let decoder = JSONDecoder() -// if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { -// decoder.dateDecodingStrategy = .iso8601 -// } -// return decoder -//} - -func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 + func mapping(map: Map) { + curPage <- map["curPage"] + datas <- map["datas"] + offset <- map["offset"] + over <- map["over"] + pageCount <- map["pageCount"] + size <- map["size"] + total <- map["total"] } - return encoder } -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) +// MARK: - DataElement +class Message: Mappable,Identifiable { + + var category, date: Int? + var fromUser: String? + var fromUserId: Int? + var fullLink: String? + var id, isRead: Int? + var link: String? + var message, niceDate: String? + var tag: String? + var title: String? + var userId: Int? + + required init?(map:Map) { + } - - @discardableResult - func responseMessageModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) + func mapping(map: Map) { + category <- map["category"] + date <- map["date"] + fromUser <- map["fromUser"] + fromUserId <- map["fromUserId"] + fullLink <- map["fullLink"] + id <- map["id"] + isRead <- map["isRead"] + link <- map["link"] + message <- map["message"] + niceDate <- map["niceDate"] + tag <- map["tag"] + title <- map["title"] + userId <- map["userId"] } } - diff --git a/WanAndroid_SwiftUI/model/ProjectModel.swift b/WanAndroid_SwiftUI/model/ProjectModel.swift index 98bae08..0219f5e 100644 --- a/WanAndroid_SwiftUI/model/ProjectModel.swift +++ b/WanAndroid_SwiftUI/model/ProjectModel.swift @@ -21,332 +21,59 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - ProjectModel -struct ProjectModel: Codable,ModelProtocol { +class ProjectModel: Mappable { - // MARK: - Helper functions for creating encoders and decoders - - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder + var data: [Project]? + var errorCode: Int? + var errorMsg: String? + + required init?(map:Map) { + } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - - let data: [Project] - let errorCode: Int - let errorMsg: String } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDatum { response in -// if let datum = response.result.value { -// ... -// } -// } // MARK: - Datum -struct Project: Codable,Identifiable { +class Project: Mappable,Identifiable { - let articleList: [JSONAny] - let author: String - let children: [JSONAny] - let courseID: Int - let cover, desc: String - let id: Int - let lisense, lisenseLink, name: String - let order, parentChapterID, type: Int - let userControlSetTop: Bool - let visible: Int - - enum CodingKeys: String, CodingKey { - case articleList, author, children - case courseID = "courseId" - case cover, desc, id, lisense, lisenseLink, name, order - case parentChapterID = "parentChapterId" - case type, userControlSetTop, visible - } -} - - - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } + var articleList: [Article]? + var author: String? + var children: [TreeItem]? + var courseId: Int? + var cover, desc: String? + var id: Int? + var lisense, lisenseLink, name: String? + var order, parentChapterId, type: Int? + var userControlSetTop: Bool? + var visible: Int? + + required init?(map:Map) { + } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) + func mapping(map: Map) { + articleList <- map["articleList"] + author <- map["author"] + children <- map["children"] + courseId <- map["courseId"] + cover <- map["cover"] + desc <- map["desc"] + id <- map["id"] + lisense <- map["lisense"] + lisenseLink <- map["lisenseLink"] + name <- map["name"] + order <- map["order"] + parentChapterId <- map["parentChapterId"] + type <- map["type"] + userControlSetTop <- map["userControlSetTop"] + visible <- map["visible"] } - @discardableResult - func responseProjectModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) - } } - -// MARK: - Encode/decode helpers - -//class JSONNull: Codable, Hashable { -// -// public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { -// return true -// } -// -// public var hashValue: Int { -// return 0 -// } -// -// public init() {} -// -// public required init(from decoder: Decoder) throws { -// let container = try decoder.singleValueContainer() -// if !container.decodeNil() { -// throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) -// } -// } -// -// public func encode(to encoder: Encoder) throws { -// var container = encoder.singleValueContainer() -// try container.encodeNil() -// } -//} -// -//class JSONCodingKey: CodingKey { -// let key: String -// -// required init?(intValue: Int) { -// return nil -// } -// -// required init?(stringValue: String) { -// key = stringValue -// } -// -// var intValue: Int? { -// return nil -// } -// -// var stringValue: String { -// return key -// } -//} -// -//class JSONAny: Codable { -// -// let value: Any -// -// static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { -// let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") -// return DecodingError.typeMismatch(JSONAny.self, context) -// } -// -// static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError { -// let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny") -// return EncodingError.invalidValue(value, context) -// } -// -// static func decode(from container: SingleValueDecodingContainer) throws -> Any { -// if let value = try? container.decode(Bool.self) { -// return value -// } -// if let value = try? container.decode(Int64.self) { -// return value -// } -// if let value = try? container.decode(Double.self) { -// return value -// } -// if let value = try? container.decode(String.self) { -// return value -// } -// if container.decodeNil() { -// return JSONNull() -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { -// if let value = try? container.decode(Bool.self) { -// return value -// } -// if let value = try? container.decode(Int64.self) { -// return value -// } -// if let value = try? container.decode(Double.self) { -// return value -// } -// if let value = try? container.decode(String.self) { -// return value -// } -// if let value = try? container.decodeNil() { -// if value { -// return JSONNull() -// } -// } -// if var container = try? container.nestedUnkeyedContainer() { -// return try decodeArray(from: &container) -// } -// if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { -// return try decodeDictionary(from: &container) -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decode(from container: inout KeyedDecodingContainer, forKey key: JSONCodingKey) throws -> Any { -// if let value = try? container.decode(Bool.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(Int64.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(Double.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(String.self, forKey: key) { -// return value -// } -// if let value = try? container.decodeNil(forKey: key) { -// if value { -// return JSONNull() -// } -// } -// if var container = try? container.nestedUnkeyedContainer(forKey: key) { -// return try decodeArray(from: &container) -// } -// if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { -// return try decodeDictionary(from: &container) -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { -// var arr: [Any] = [] -// while !container.isAtEnd { -// let value = try decode(from: &container) -// arr.append(value) -// } -// return arr -// } -// -// static func decodeDictionary(from container: inout KeyedDecodingContainer) throws -> [String: Any] { -// var dict = [String: Any]() -// for key in container.allKeys { -// let value = try decode(from: &container, forKey: key) -// dict[key.stringValue] = value -// } -// return dict -// } -// -// static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws { -// for value in array { -// if let value = value as? Bool { -// try container.encode(value) -// } else if let value = value as? Int64 { -// try container.encode(value) -// } else if let value = value as? Double { -// try container.encode(value) -// } else if let value = value as? String { -// try container.encode(value) -// } else if value is JSONNull { -// try container.encodeNil() -// } else if let value = value as? [Any] { -// var container = container.nestedUnkeyedContainer() -// try encode(to: &container, array: value) -// } else if let value = value as? [String: Any] { -// var container = container.nestedContainer(keyedBy: JSONCodingKey.self) -// try encode(to: &container, dictionary: value) -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// } -// -// static func encode(to container: inout KeyedEncodingContainer, dictionary: [String: Any]) throws { -// for (key, value) in dictionary { -// let key = JSONCodingKey(stringValue: key)! -// if let value = value as? Bool { -// try container.encode(value, forKey: key) -// } else if let value = value as? Int64 { -// try container.encode(value, forKey: key) -// } else if let value = value as? Double { -// try container.encode(value, forKey: key) -// } else if let value = value as? String { -// try container.encode(value, forKey: key) -// } else if value is JSONNull { -// try container.encodeNil(forKey: key) -// } else if let value = value as? [Any] { -// var container = container.nestedUnkeyedContainer(forKey: key) -// try encode(to: &container, array: value) -// } else if let value = value as? [String: Any] { -// var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) -// try encode(to: &container, dictionary: value) -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// } -// -// static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws { -// if let value = value as? Bool { -// try container.encode(value) -// } else if let value = value as? Int64 { -// try container.encode(value) -// } else if let value = value as? Double { -// try container.encode(value) -// } else if let value = value as? String { -// try container.encode(value) -// } else if value is JSONNull { -// try container.encodeNil() -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// -// public required init(from decoder: Decoder) throws { -// if var arrayContainer = try? decoder.unkeyedContainer() { -// self.value = try JSONAny.decodeArray(from: &arrayContainer) -// } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { -// self.value = try JSONAny.decodeDictionary(from: &container) -// } else { -// let container = try decoder.singleValueContainer() -// self.value = try JSONAny.decode(from: container) -// } -// } -// -// public func encode(to encoder: Encoder) throws { -// if let arr = self.value as? [Any] { -// var container = encoder.unkeyedContainer() -// try JSONAny.encode(to: &container, array: arr) -// } else if let dict = self.value as? [String: Any] { -// var container = encoder.container(keyedBy: JSONCodingKey.self) -// try JSONAny.encode(to: &container, dictionary: dict) -// } else { -// var container = encoder.singleValueContainer() -// try JSONAny.encode(to: &container, value: self.value) -// } -// } -//} -// diff --git a/WanAndroid_SwiftUI/model/ProjectSonModel.swift b/WanAndroid_SwiftUI/model/ProjectSonModel.swift index cc0d81d..45e2655 100644 --- a/WanAndroid_SwiftUI/model/ProjectSonModel.swift +++ b/WanAndroid_SwiftUI/model/ProjectSonModel.swift @@ -21,385 +21,43 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - ProjectSonModel -struct ProjectSonModel: Codable ,ModelProtocol{ - // MARK: - Helper functions for creating encoders and decoders - - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder +class ProjectSonModel: Mappable{ + + var data: ProjectSonModelData? + var errorCode: Int? + var errorMsg: String? + + required init?(map:Map) { + } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - - let data: ProjectSonModelData - let errorCode: Int - let errorMsg: String } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseProjectSonModelData { response in -// if let projectSonModelData = response.result.value { -// ... -// } -// } - // MARK: - ProjectSonModelData -struct ProjectSonModelData: Codable { - let curPage: Int - let datas: [Article] - let offset: Int - let over: Bool - let pageCount, size, total: Int -} -// -//// -//// To parse values from Alamofire responses: -//// -//// Alamofire.request(url).responseDataElement { response in -//// if let dataElement = response.result.value { -//// ... -//// } -//// } -// -//// MARK: - DataElement -//struct Article: Codable { -// let adminAdd: Bool -// let apkLink: String -// let audit: Int -// let author: String -// let canEdit: Bool -// let chapterID: Int -// let chapterName: ChapterName -// let collect: Bool -// let courseID: Int -// let desc, descMd, envelopePic: String -// let fresh: Bool -// let host: String -// let id: Int -// let isAdminAdd: Bool -// let link: String -// let niceDate, niceShareDate, origin, dataPrefix: String -// let projectLink: String -// let publishTime, realSuperChapterID, selfVisible: Int -// let shareDate: Int? -// let shareUser: ShareUser -// let superChapterID: Int -// let superChapterName: SuperChapterName -// let tags: [JSONAny] -// let title: String -// let type, userID, visible, zan: Int -// -// enum CodingKeys: String, CodingKey { -// case adminAdd, apkLink, audit, author, canEdit -// case chapterID = "chapterId" -// case chapterName, collect -// case courseID = "courseId" -// case desc, descMd, envelopePic, fresh, host, id, isAdminAdd, link, niceDate, niceShareDate, origin -// case dataPrefix = "prefix" -// case projectLink, publishTime -// case realSuperChapterID = "realSuperChapterId" -// case selfVisible, shareDate, shareUser -// case superChapterID = "superChapterId" -// case superChapterName, tags, title, type -// case userID = "userId" -// case visible, zan -// } -//} -// -//enum ChapterName: String, Codable { -// case androidStudio相关 = "Android Studio相关" -//} -// -//enum ShareUser: String, Codable { -// case empty = "" -// case goweii = "goweii" -// case 鸿洋 = "鸿洋" -//} -// -//enum SuperChapterName: String, Codable { -// case 开发环境 = "开发环境" -//} - - - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) +class ProjectSonModelData: Mappable { + var curPage: Int? + var datas: [Article]? + var offset: Int? + var over: Bool? + var pageCount, size, total: Int? + + required init?(map:Map) { + } - - @discardableResult - func responseProjectSonModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) + func mapping(map: Map) { + curPage <- map["curPage"] + datas <- map["datas"] + offset <- map["offset"] + over <- map["over"] + pageCount <- map["pageCount"] + size <- map["size"] + total <- map["total"] } } - -//// MARK: - Encode/decode helpers -// -//class JSONNull: Codable, Hashable { -// -// public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { -// return true -// } -// -// public var hashValue: Int { -// return 0 -// } -// -// public init() {} -// -// public required init(from decoder: Decoder) throws { -// let container = try decoder.singleValueContainer() -// if !container.decodeNil() { -// throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) -// } -// } -// -// public func encode(to encoder: Encoder) throws { -// var container = encoder.singleValueContainer() -// try container.encodeNil() -// } -//} -// -//class JSONCodingKey: CodingKey { -// let key: String -// -// required init?(intValue: Int) { -// return nil -// } -// -// required init?(stringValue: String) { -// key = stringValue -// } -// -// var intValue: Int? { -// return nil -// } -// -// var stringValue: String { -// return key -// } -//} -// -//class JSONAny: Codable { -// -// let value: Any -// -// static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { -// let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") -// return DecodingError.typeMismatch(JSONAny.self, context) -// } -// -// static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError { -// let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny") -// return EncodingError.invalidValue(value, context) -// } -// -// static func decode(from container: SingleValueDecodingContainer) throws -> Any { -// if let value = try? container.decode(Bool.self) { -// return value -// } -// if let value = try? container.decode(Int64.self) { -// return value -// } -// if let value = try? container.decode(Double.self) { -// return value -// } -// if let value = try? container.decode(String.self) { -// return value -// } -// if container.decodeNil() { -// return JSONNull() -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { -// if let value = try? container.decode(Bool.self) { -// return value -// } -// if let value = try? container.decode(Int64.self) { -// return value -// } -// if let value = try? container.decode(Double.self) { -// return value -// } -// if let value = try? container.decode(String.self) { -// return value -// } -// if let value = try? container.decodeNil() { -// if value { -// return JSONNull() -// } -// } -// if var container = try? container.nestedUnkeyedContainer() { -// return try decodeArray(from: &container) -// } -// if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { -// return try decodeDictionary(from: &container) -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decode(from container: inout KeyedDecodingContainer, forKey key: JSONCodingKey) throws -> Any { -// if let value = try? container.decode(Bool.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(Int64.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(Double.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(String.self, forKey: key) { -// return value -// } -// if let value = try? container.decodeNil(forKey: key) { -// if value { -// return JSONNull() -// } -// } -// if var container = try? container.nestedUnkeyedContainer(forKey: key) { -// return try decodeArray(from: &container) -// } -// if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { -// return try decodeDictionary(from: &container) -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { -// var arr: [Any] = [] -// while !container.isAtEnd { -// let value = try decode(from: &container) -// arr.append(value) -// } -// return arr -// } -// -// static func decodeDictionary(from container: inout KeyedDecodingContainer) throws -> [String: Any] { -// var dict = [String: Any]() -// for key in container.allKeys { -// let value = try decode(from: &container, forKey: key) -// dict[key.stringValue] = value -// } -// return dict -// } -// -// static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws { -// for value in array { -// if let value = value as? Bool { -// try container.encode(value) -// } else if let value = value as? Int64 { -// try container.encode(value) -// } else if let value = value as? Double { -// try container.encode(value) -// } else if let value = value as? String { -// try container.encode(value) -// } else if value is JSONNull { -// try container.encodeNil() -// } else if let value = value as? [Any] { -// var container = container.nestedUnkeyedContainer() -// try encode(to: &container, array: value) -// } else if let value = value as? [String: Any] { -// var container = container.nestedContainer(keyedBy: JSONCodingKey.self) -// try encode(to: &container, dictionary: value) -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// } -// -// static func encode(to container: inout KeyedEncodingContainer, dictionary: [String: Any]) throws { -// for (key, value) in dictionary { -// let key = JSONCodingKey(stringValue: key)! -// if let value = value as? Bool { -// try container.encode(value, forKey: key) -// } else if let value = value as? Int64 { -// try container.encode(value, forKey: key) -// } else if let value = value as? Double { -// try container.encode(value, forKey: key) -// } else if let value = value as? String { -// try container.encode(value, forKey: key) -// } else if value is JSONNull { -// try container.encodeNil(forKey: key) -// } else if let value = value as? [Any] { -// var container = container.nestedUnkeyedContainer(forKey: key) -// try encode(to: &container, array: value) -// } else if let value = value as? [String: Any] { -// var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) -// try encode(to: &container, dictionary: value) -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// } -// -// static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws { -// if let value = value as? Bool { -// try container.encode(value) -// } else if let value = value as? Int64 { -// try container.encode(value) -// } else if let value = value as? Double { -// try container.encode(value) -// } else if let value = value as? String { -// try container.encode(value) -// } else if value is JSONNull { -// try container.encodeNil() -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// -// public required init(from decoder: Decoder) throws { -// if var arrayContainer = try? decoder.unkeyedContainer() { -// self.value = try JSONAny.decodeArray(from: &arrayContainer) -// } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { -// self.value = try JSONAny.decodeDictionary(from: &container) -// } else { -// let container = try decoder.singleValueContainer() -// self.value = try JSONAny.decode(from: container) -// } -// } -// -// public func encode(to encoder: Encoder) throws { -// if let arr = self.value as? [Any] { -// var container = encoder.unkeyedContainer() -// try JSONAny.encode(to: &container, array: arr) -// } else if let dict = self.value as? [String: Any] { -// var container = encoder.container(keyedBy: JSONCodingKey.self) -// try JSONAny.encode(to: &container, dictionary: dict) -// } else { -// var container = encoder.singleValueContainer() -// try JSONAny.encode(to: &container, value: self.value) -// } -// } -//} -// diff --git a/WanAndroid_SwiftUI/model/TreeModel.swift b/WanAndroid_SwiftUI/model/TreeModel.swift index 5dc17cb..c8d1fda 100644 --- a/WanAndroid_SwiftUI/model/TreeModel.swift +++ b/WanAndroid_SwiftUI/model/TreeModel.swift @@ -21,416 +21,63 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - TreeModel -struct TreeModel: Codable ,ModelProtocol{ +class TreeModel: Mappable{ // MARK: - Helper functions for creating encoders and decoders - - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder - } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder - } - let data: [TreeItem] - let errorCode: Int - let errorMsg: String -} - -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDatum { response in -// if let datum = response.result.value { -// ... -// } -// } - -// MARK: - Datum -struct TreeItem: Codable,Identifiable { - let articleList: [ArticleList] - let author: DatumAuthor - let children: [TreeItem] - let courseID: Int - let cover: String - let desc: String - let id: Int - let lisense: Lisense - let lisenseLink: String - let name: String - let order, parentChapterID, type: Int - let userControlSetTop: Bool - let visible: Int - - enum CodingKeys: String, CodingKey { - case articleList, author, children - case courseID = "courseId" - case cover, desc, id, lisense, lisenseLink, name, order - case parentChapterID = "parentChapterId" - case type, userControlSetTop, visible - } -} - -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseArticleList { response in -// if let articleList = response.result.value { -// ... -// } -// } - -// MARK: - ArticleList -struct ArticleList: Codable,Identifiable { - let adminAdd: Bool - let apkLink: String - let audit: Int - let author: ArticleListAuthor - let canEdit: Bool - let chapterID: Int - let chapterName: String - let collect: Bool - let courseID: Int - let desc, descMd, envelopePic: String - let fresh: Bool - let host: String - let id: Int - let isAdminAdd: Bool - let link: String - let niceDate, niceShareDate, origin, articleListPrefix: String - let projectLink: String - let publishTime, realSuperChapterID, selfVisible, shareDate: Int - let shareUser: String - let superChapterID: Int - let superChapterName: SuperChapterName - let tags: [JSONAny] - let title: String - let type, userID, visible, zan: Int - - enum CodingKeys: String, CodingKey { - case adminAdd, apkLink, audit, author, canEdit - case chapterID = "chapterId" - case chapterName, collect - case courseID = "courseId" - case desc, descMd, envelopePic, fresh, host, id, isAdminAdd, link, niceDate, niceShareDate, origin - case articleListPrefix = "prefix" - case projectLink, publishTime - case realSuperChapterID = "realSuperChapterId" - case selfVisible, shareDate, shareUser - case superChapterID = "superChapterId" - case superChapterName, tags, title, type - case userID = "userId" - case visible, zan + var data: [TreeItem]? + var errorCode: Int? + var errorMsg: String? + + + required init?(map:Map) { + } -} - -enum ArticleListAuthor: String, Codable { - case 鸿洋 = "鸿洋" -} - -enum SuperChapterName: String, Codable { - case androidFramework学习路径 = "Android framework - 学习路径" - case androidGradle学习路径 = "Android Gradle - 学习路径" - case android性能优化进阶篇学习路径 = "Android 性能优化 - 进阶篇 - 学习路径" - case android性能优化长期分享BaguTree组织 = "Android 性能优化-长期分享-BaguTree组织" - case android自定义View学习路径 = "Android自定义View - 学习路径" - case 大厂对外分享学习路径 = "大厂对外分享 - 学习路径" - case 高级编程NdkJNI学习路径 = "高级编程NDK/JNI - 学习路径" -} - -enum DatumAuthor: String, Codable { - case baguTree组织 = "BaguTree组织" - case empty = "" - case 阮一峰 = "阮一峰" -} - -enum Lisense: String, Codable { - case empty = "" - case 知识共享署名相同方式共享30协议 = "知识共享 署名-相同方式共享 3.0协议" -} - -func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - return decoder } -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - return Result { try newJSONDecoder().decode(T.self, from: data) } - } +// MARK: - Datum +class TreeItem: Mappable,Identifiable { + var articleList: [Article]? + var author: String? + var children: [TreeItem]? + var courseID: Int? + var cover: String? + var desc: String? + var id: Int? + var lisense: String? + var lisenseLink: String? + var name: String? + var order, parentChapterID, type: Int? + var userControlSetTop: Bool? + var visible: Int? + + required init?(map:Map) { + } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) + func mapping(map: Map) { + articleList <- map["articleList"] + author <- map["author"] + children <- map["children"] + courseID <- map["courseID"] + cover <- map["cover"] + desc <- map["desc"] + id <- map["id"] + lisense <- map["lisense"] + lisenseLink <- map["lisenseLink"] + name <- map["name"] + order <- map["order"] + parentChapterID <- map["parentChapterID"] + type <- map["type"] + userControlSetTop <- map["userControlSetTop"] + visible <- map["visible"] } - @discardableResult - func responseTreeModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) - } } - -// MARK: - Encode/decode helpers - -//class JSONNull: Codable, Hashable { -// -// public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { -// return true -// } -// -// public var hashValue: Int { -// return 0 -// } -// -// public init() {} -// -// public required init(from decoder: Decoder) throws { -// let container = try decoder.singleValueContainer() -// if !container.decodeNil() { -// throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) -// } -// } -// -// public func encode(to encoder: Encoder) throws { -// var container = encoder.singleValueContainer() -// try container.encodeNil() -// } -//} - -//class JSONCodingKey: CodingKey { -// let key: String -// -// required init?(intValue: Int) { -// return nil -// } -// -// required init?(stringValue: String) { -// key = stringValue -// } -// -// var intValue: Int? { -// return nil -// } -// -// var stringValue: String { -// return key -// } -//} -// -//class JSONAny: Codable { -// -// let value: Any -// -// static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { -// let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") -// return DecodingError.typeMismatch(JSONAny.self, context) -// } -// -// static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError { -// let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny") -// return EncodingError.invalidValue(value, context) -// } -// -// static func decode(from container: SingleValueDecodingContainer) throws -> Any { -// if let value = try? container.decode(Bool.self) { -// return value -// } -// if let value = try? container.decode(Int64.self) { -// return value -// } -// if let value = try? container.decode(Double.self) { -// return value -// } -// if let value = try? container.decode(String.self) { -// return value -// } -// if container.decodeNil() { -// return JSONNull() -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { -// if let value = try? container.decode(Bool.self) { -// return value -// } -// if let value = try? container.decode(Int64.self) { -// return value -// } -// if let value = try? container.decode(Double.self) { -// return value -// } -// if let value = try? container.decode(String.self) { -// return value -// } -// if let value = try? container.decodeNil() { -// if value { -// return JSONNull() -// } -// } -// if var container = try? container.nestedUnkeyedContainer() { -// return try decodeArray(from: &container) -// } -// if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { -// return try decodeDictionary(from: &container) -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decode(from container: inout KeyedDecodingContainer, forKey key: JSONCodingKey) throws -> Any { -// if let value = try? container.decode(Bool.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(Int64.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(Double.self, forKey: key) { -// return value -// } -// if let value = try? container.decode(String.self, forKey: key) { -// return value -// } -// if let value = try? container.decodeNil(forKey: key) { -// if value { -// return JSONNull() -// } -// } -// if var container = try? container.nestedUnkeyedContainer(forKey: key) { -// return try decodeArray(from: &container) -// } -// if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { -// return try decodeDictionary(from: &container) -// } -// throw decodingError(forCodingPath: container.codingPath) -// } -// -// static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { -// var arr: [Any] = [] -// while !container.isAtEnd { -// let value = try decode(from: &container) -// arr.append(value) -// } -// return arr -// } -// -// static func decodeDictionary(from container: inout KeyedDecodingContainer) throws -> [String: Any] { -// var dict = [String: Any]() -// for key in container.allKeys { -// let value = try decode(from: &container, forKey: key) -// dict[key.stringValue] = value -// } -// return dict -// } -// -// static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws { -// for value in array { -// if let value = value as? Bool { -// try container.encode(value) -// } else if let value = value as? Int64 { -// try container.encode(value) -// } else if let value = value as? Double { -// try container.encode(value) -// } else if let value = value as? String { -// try container.encode(value) -// } else if value is JSONNull { -// try container.encodeNil() -// } else if let value = value as? [Any] { -// var container = container.nestedUnkeyedContainer() -// try encode(to: &container, array: value) -// } else if let value = value as? [String: Any] { -// var container = container.nestedContainer(keyedBy: JSONCodingKey.self) -// try encode(to: &container, dictionary: value) -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// } -// -// static func encode(to container: inout KeyedEncodingContainer, dictionary: [String: Any]) throws { -// for (key, value) in dictionary { -// let key = JSONCodingKey(stringValue: key)! -// if let value = value as? Bool { -// try container.encode(value, forKey: key) -// } else if let value = value as? Int64 { -// try container.encode(value, forKey: key) -// } else if let value = value as? Double { -// try container.encode(value, forKey: key) -// } else if let value = value as? String { -// try container.encode(value, forKey: key) -// } else if value is JSONNull { -// try container.encodeNil(forKey: key) -// } else if let value = value as? [Any] { -// var container = container.nestedUnkeyedContainer(forKey: key) -// try encode(to: &container, array: value) -// } else if let value = value as? [String: Any] { -// var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) -// try encode(to: &container, dictionary: value) -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// } -// -// static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws { -// if let value = value as? Bool { -// try container.encode(value) -// } else if let value = value as? Int64 { -// try container.encode(value) -// } else if let value = value as? Double { -// try container.encode(value) -// } else if let value = value as? String { -// try container.encode(value) -// } else if value is JSONNull { -// try container.encodeNil() -// } else { -// throw encodingError(forValue: value, codingPath: container.codingPath) -// } -// } -// -// public required init(from decoder: Decoder) throws { -// if var arrayContainer = try? decoder.unkeyedContainer() { -// self.value = try JSONAny.decodeArray(from: &arrayContainer) -// } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { -// self.value = try JSONAny.decodeDictionary(from: &container) -// } else { -// let container = try decoder.singleValueContainer() -// self.value = try JSONAny.decode(from: container) -// } -// } -// -// public func encode(to encoder: Encoder) throws { -// if let arr = self.value as? [Any] { -// var container = encoder.unkeyedContainer() -// try JSONAny.encode(to: &container, array: arr) -// } else if let dict = self.value as? [String: Any] { -// var container = encoder.container(keyedBy: JSONCodingKey.self) -// try JSONAny.encode(to: &container, dictionary: dict) -// } else { -// var container = encoder.singleValueContainer() -// try JSONAny.encode(to: &container, value: self.value) -// } -// } -//} diff --git a/WanAndroid_SwiftUI/model/UserModel.swift b/WanAndroid_SwiftUI/model/UserModel.swift index 5a978db..768e802 100644 --- a/WanAndroid_SwiftUI/model/UserModel.swift +++ b/WanAndroid_SwiftUI/model/UserModel.swift @@ -21,324 +21,58 @@ import Foundation import Alamofire +import ObjectMapper // MARK: - UserModel -struct UserModel: Codable ,ModelProtocol{ - // MARK: - Helper functions for creating encoders and decoders - - func newJSONDecoder() -> JSONDecoder { - let decoder = JSONDecoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - decoder.dateDecodingStrategy = .iso8601 - } - return decoder +class UserModel: Mappable{ + + var data: User? + var errorCode: Int? + var errorMsg: String? + required init?(map:Map) { + } - - func newJSONEncoder() -> JSONEncoder { - let encoder = JSONEncoder() - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { - encoder.dateEncodingStrategy = .iso8601 - } - return encoder + func mapping(map: Map) { + data <- map["data"] + errorCode <- map["errorCode"] + errorMsg <- map["errorMsg"] } - let data: User? - let errorCode: Int? - let errorMsg: String? } -// -// To parse values from Alamofire responses: -// -// Alamofire.request(url).responseDataClass { response in -// if let dataClass = response.result.value { -// ... -// } -// } // MARK: - DataClass -struct User: Codable,Identifiable { - let admin: Bool - let chapterTops: [JSONAny]? - let coinCount: Int - let collectIDS: [Int] - let email, icon: String - let id: Int - let nickname, password, publicName, token: String - let type: Int - let username: String - - enum CodingKeys: String, CodingKey { - case admin, chapterTops, coinCount - case collectIDS = "collectIds" - case email, icon, id, nickname, password, publicName, token, type, username - } -} - - - -// MARK: - Alamofire response handlers - -extension DataRequest { - fileprivate func decodableResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - guard error == nil else { return .failure(error!) } - - guard let data = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return Result { try newJSONDecoder().decode(T.self, from: data) } - } - } - - @discardableResult - fileprivate func responseDecodable(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler) - } - - @discardableResult - func responseUserModel(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return responseDecodable(queue: queue, completionHandler: completionHandler) - } -} - -// MARK: - Encode/decode helpers - -@objcMembers class JSONNull: NSObject, Codable { - - public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { - return true - } - - override public init() {} - - public required init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - if !container.decodeNil() { - throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - try container.encodeNil() - } -} - -class JSONCodingKey: CodingKey { - let key: String - - required init?(intValue: Int) { - return nil - } - - required init?(stringValue: String) { - key = stringValue - } - - var intValue: Int? { - return nil +class User: Mappable ,Identifiable{ + var admin: Bool? + var chapterTops: [Int]? + var coinCount: Int? + var collectIDS: [Int]? + var email, icon: String? + var id: Int? + var nickname, password, publicName, token: String? + var type: Int? + var username: String? + + required init?(map:Map) { + } - - var stringValue: String { - return key + + func mapping(map: Map) { + admin <- map["admin"] + chapterTops <- map["chapterTops"] + coinCount <- map["coinCount"] + collectIDS <- map["collectIDS"] + email <- map["email"] + icon <- map["icon"] + id <- map["id"] + nickname <- map["nickname"] + password <- map["password"] + publicName <- map["publicName"] + token <- map["token"] + type <- map["type"] + username <- map["username"] } } -@objcMembers class JSONAny: NSObject, Codable { - - let value: Any - - static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { - let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") - return DecodingError.typeMismatch(JSONAny.self, context) - } - - static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError { - let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny") - return EncodingError.invalidValue(value, context) - } - - static func decode(from container: SingleValueDecodingContainer) throws -> Any { - if let value = try? container.decode(Bool.self) { - return value - } - if let value = try? container.decode(Int64.self) { - return value - } - if let value = try? container.decode(Double.self) { - return value - } - if let value = try? container.decode(String.self) { - return value - } - if container.decodeNil() { - return JSONNull() - } - throw decodingError(forCodingPath: container.codingPath) - } - - static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { - if let value = try? container.decode(Bool.self) { - return value - } - if let value = try? container.decode(Int64.self) { - return value - } - if let value = try? container.decode(Double.self) { - return value - } - if let value = try? container.decode(String.self) { - return value - } - if let value = try? container.decodeNil() { - if value { - return JSONNull() - } - } - if var container = try? container.nestedUnkeyedContainer() { - return try decodeArray(from: &container) - } - if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { - return try decodeDictionary(from: &container) - } - throw decodingError(forCodingPath: container.codingPath) - } - - static func decode(from container: inout KeyedDecodingContainer, forKey key: JSONCodingKey) throws -> Any { - if let value = try? container.decode(Bool.self, forKey: key) { - return value - } - if let value = try? container.decode(Int64.self, forKey: key) { - return value - } - if let value = try? container.decode(Double.self, forKey: key) { - return value - } - if let value = try? container.decode(String.self, forKey: key) { - return value - } - if let value = try? container.decodeNil(forKey: key) { - if value { - return JSONNull() - } - } - if var container = try? container.nestedUnkeyedContainer(forKey: key) { - return try decodeArray(from: &container) - } - if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { - return try decodeDictionary(from: &container) - } - throw decodingError(forCodingPath: container.codingPath) - } - - static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { - var arr: [Any] = [] - while !container.isAtEnd { - let value = try decode(from: &container) - arr.append(value) - } - return arr - } - - static func decodeDictionary(from container: inout KeyedDecodingContainer) throws -> [String: Any] { - var dict = [String: Any]() - for key in container.allKeys { - let value = try decode(from: &container, forKey: key) - dict[key.stringValue] = value - } - return dict - } - - static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws { - for value in array { - if let value = value as? Bool { - try container.encode(value) - } else if let value = value as? Int64 { - try container.encode(value) - } else if let value = value as? Double { - try container.encode(value) - } else if let value = value as? String { - try container.encode(value) - } else if value is JSONNull { - try container.encodeNil() - } else if let value = value as? [Any] { - var container = container.nestedUnkeyedContainer() - try encode(to: &container, array: value) - } else if let value = value as? [String: Any] { - var container = container.nestedContainer(keyedBy: JSONCodingKey.self) - try encode(to: &container, dictionary: value) - } else { - throw encodingError(forValue: value, codingPath: container.codingPath) - } - } - } - - static func encode(to container: inout KeyedEncodingContainer, dictionary: [String: Any]) throws { - for (key, value) in dictionary { - let key = JSONCodingKey(stringValue: key)! - if let value = value as? Bool { - try container.encode(value, forKey: key) - } else if let value = value as? Int64 { - try container.encode(value, forKey: key) - } else if let value = value as? Double { - try container.encode(value, forKey: key) - } else if let value = value as? String { - try container.encode(value, forKey: key) - } else if value is JSONNull { - try container.encodeNil(forKey: key) - } else if let value = value as? [Any] { - var container = container.nestedUnkeyedContainer(forKey: key) - try encode(to: &container, array: value) - } else if let value = value as? [String: Any] { - var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) - try encode(to: &container, dictionary: value) - } else { - throw encodingError(forValue: value, codingPath: container.codingPath) - } - } - } - - static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws { - if let value = value as? Bool { - try container.encode(value) - } else if let value = value as? Int64 { - try container.encode(value) - } else if let value = value as? Double { - try container.encode(value) - } else if let value = value as? String { - try container.encode(value) - } else if value is JSONNull { - try container.encodeNil() - } else { - throw encodingError(forValue: value, codingPath: container.codingPath) - } - } - - public required init(from decoder: Decoder) throws { - if var arrayContainer = try? decoder.unkeyedContainer() { - self.value = try JSONAny.decodeArray(from: &arrayContainer) - } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { - self.value = try JSONAny.decodeDictionary(from: &container) - } else { - let container = try decoder.singleValueContainer() - self.value = try JSONAny.decode(from: container) - } - } - - public func encode(to encoder: Encoder) throws { - if let arr = self.value as? [Any] { - var container = encoder.unkeyedContainer() - try JSONAny.encode(to: &container, array: arr) - } else if let dict = self.value as? [String: Any] { - var container = encoder.container(keyedBy: JSONCodingKey.self) - try JSONAny.encode(to: &container, dictionary: dict) - } else { - var container = encoder.singleValueContainer() - try JSONAny.encode(to: &container, value: self.value) - } - } -} diff --git a/WanAndroid_SwiftUI/utils/Const.swift b/WanAndroid_SwiftUI/utils/Const.swift new file mode 100644 index 0000000..b15b1a7 --- /dev/null +++ b/WanAndroid_SwiftUI/utils/Const.swift @@ -0,0 +1,73 @@ +// +// Const.swift +// WanAndroid_SwiftUI +// +// Created by zxc on 2023/11/29. +// + +import Foundation +import ObjectMapper + +/** + @desc:常量工具类-模拟数据 + */ +class Const{ + static let shared = Const() + + private init() { + // 不要忘记把构造器变成私有 + } + + + //1-轮播图数据 + func getBannerData() -> BannerModel { + let bannerMapper = Mapper(); + let bannerString = "{\"data\":[{\"desc\":\"我们支持订阅啦~\",\"id\":30,\"imagePath\":\"https://www.wanandroid.com/blogimgs/42da12d8-de56-4439-b40c-eab66c227a4b.png\",\"isVisible\":1,\"order\":2,\"title\":\"我们支持订阅啦~\",\"type\":0,\"url\":\"https://www.wanandroid.com/blog/show/3352\"},{\"desc\":\"\",\"id\":6,\"imagePath\":\"https://www.wanandroid.com/blogimgs/62c1bd68-b5f3-4a3c-a649-7ca8c7dfabe6.png\",\"isVisible\":1,\"order\":1,\"title\":\"我们新增了一个常用导航Tab~\",\"type\":1,\"url\":\"https://www.wanandroid.com/navi\"},{\"desc\":\"一起来做个App吧\",\"id\":10,\"imagePath\":\"https://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png\",\"isVisible\":1,\"order\":1,\"title\":\"一起来做个App吧\",\"type\":1,\"url\":\"https://www.wanandroid.com/blog/show/2\"}],\"errorCode\":0,\"errorMsg\":\"\"}"; + let banner = bannerMapper.map(JSONString: bannerString); + return banner! + } + + //2-Article-列表 + func getArticleModel()->ArticleModel{ + let articleModelMapper = Mapper() + + let articleModelString = "{\"data\":{\"curPage\":2,\"datas\":[{\"adminAdd\":false,\"apkLink\":\"\",\"audit\":1,\"author\":\"\",\"canEdit\":false,\"chapterId\":502,\"chapterName\":\"自助\",\"collect\":false,\"courseId\":13,\"desc\":\"\",\"descMd\":\"\",\"envelopePic\":\"\",\"fresh\":false,\"host\":\"\",\"id\":27605,\"isAdminAdd\":false,\"link\":\"https://jimmysun.blog.csdn.net/article/details/134557842\",\"niceDate\":\"2023-11-24 14:36\",\"niceShareDate\":\"2023-11-24 14:35\",\"origin\":\"\",\"prefix\":\"\",\"projectLink\":\"\",\"publishTime\":1700807770000,\"realSuperChapterId\":493,\"selfVisible\":0,\"shareDate\":1700807757000,\"shareUser\":\"孙强 Jimmy\",\"superChapterId\":494,\"superChapterName\":\"广场Tab\",\"tags\":[],\"title\":\"AIDL 如何分片传输大量 Parcelable 数据列表\",\"type\":0,\"userId\":24124,\"visible\":1,\"zan\":0},{\"adminAdd\":false,\"apkLink\":\"\",\"audit\":1,\"author\":\"鸿洋\",\"canEdit\":false,\"chapterId\":408,\"chapterName\":\"鸿洋\",\"collect\":false,\"courseId\":13,\"desc\":\"\",\"descMd\":\"\",\"envelopePic\":\"\",\"fresh\":false,\"host\":\"\",\"id\":27624,\"isAdminAdd\":false,\"link\":\"https://mp.weixin.qq.com/s/mXGTlqv0MX-TRVwlqK43Eg\",\"niceDate\":\"2023-11-24 00:00\",\"niceShareDate\":\"1天前\",\"origin\":\"\",\"prefix\":\"\",\"projectLink\":\"\",\"publishTime\":1700755200000,\"realSuperChapterId\":407,\"selfVisible\":0,\"shareDate\":1701134018000,\"shareUser\":\"\",\"superChapterId\":408,\"superChapterName\":\"公众号\",\"tags\":[{\"name\":\"公众号\",\"url\":\"/wxarticle/list/408/1\"}],\"title\":\"硬核介绍Android画面渲染,从硬件到软件\",\"type\":0,\"userId\":-1,\"visible\":1,\"zan\":0}],\"offset\":20,\"over\":false,\"pageCount\":746,\"size\":20,\"total\":14905},\"errorCode\":0,\"errorMsg\":\"\"}"; + + let articleModel = articleModelMapper.map(JSONString: articleModelString); + return articleModel!; + + } + + // 3-AritcleCell(Article) + func getArticle()->Article { + let articleMapper = Mapper
() + + let articleString = "{\"adminAdd\":false,\"apkLink\":\"\",\"audit\":1,\"author\":\"鸿洋\",\"canEdit\":false,\"chapterId\":408,\"chapterName\":\"鸿洋\",\"collect\":false,\"courseId\":13,\"desc\":\"\",\"descMd\":\"\",\"envelopePic\":\"\",\"fresh\":false,\"host\":\"\",\"id\":27624,\"isAdminAdd\":false,\"link\":\"https://mp.weixin.qq.com/s/mXGTlqv0MX-TRVwlqK43Eg\",\"niceDate\":\"2023-11-24 00:00\",\"niceShareDate\":\"1天前\",\"origin\":\"\",\"prefix\":\"\",\"projectLink\":\"\",\"publishTime\":1700755200000,\"realSuperChapterId\":407,\"selfVisible\":0,\"shareDate\":1701134018000,\"shareUser\":\"\",\"superChapterId\":408,\"superChapterName\":\"公众号\",\"tags\":[{\"name\":\"公众号\",\"url\":\"/wxarticle/list/408/1\"}],\"title\":\"硬核介绍Android画面渲染,从硬件到软件\",\"type\":0,\"userId\":-1,\"visible\":1,\"zan\":0}"; + + let article = articleMapper.map(JSONString: articleString); + return article!; + } + + //4-MessageItem + func getMessage()->Message{ + let messageMapper = Mapper() + let messageString = "{\"category\":2,\"date\":1700931931000,\"fromUser\":\"zhuozui\",\"fromUserId\":141917,\"fullLink\":\"https://wanandroid.com/wenda/show/8857\",\"id\":776994,\"isRead\":1,\"link\":\"/wenda/show/8857\",\"message\":\"在 ConstraintLayout 中使用 Barrier 时, 如果 Barrier 所包含的控件有 visibility 属性为 gone 的情况, Barrier约束会失效,有解决的办法吗?\",\"niceDate\":\"2023-11-26 01:05\",\"tag\":\"新回答\",\"title\":\"回答了:每日一问 问答征集\",\"userId\":26707}"; + + let message = messageMapper.map(JSONString: messageString); + return message!; + + } + + //5-MessageModel + func getMessageModel()->MessageModel{ + let messageModelMapper = Mapper() + let messageModelString = "{\"data\":{\"curPage\":1,\"datas\":[{\"category\":2,\"date\":1700931931000,\"fromUser\":\"zhuozui\",\"fromUserId\":141917,\"fullLink\":\"https://wanandroid.com/wenda/show/8857\",\"id\":776994,\"isRead\":1,\"link\":\"/wenda/show/8857\",\"message\":\"在 ConstraintLayout 中使用 Barrier 时, 如果 Barrier 所包含的控件有 visibility 属性为 gone 的情况, Barrier约束会失效,有解决的办法吗?\",\"niceDate\":\"2023-11-26 01:05\",\"tag\":\"新回答\",\"title\":\"回答了:每日一问 问答征集\",\"userId\":26707},{\"category\":2,\"date\":1700888159000,\"fromUser\":\"yeqiu000\",\"fromUserId\":3778,\"fullLink\":\"https://wanandroid.com/wenda/show/8857\",\"id\":775964,\"isRead\":1,\"link\":\"/wenda/show/8857\",\"message\":\"最近在做SplashScreen的适配,遇到一些问题,有没有大佬指点一下。我看了一些介绍SplashScreen的文章,似乎没有办法使用一张图片作为启动图,类似微信那样的...\",\"niceDate\":\"2023-11-25 12:55\",\"tag\":\"新回答\",\"title\":\"回答了:每日一问 问答征集\",\"userId\":26707}],\"offset\":0,\"over\":false,\"pageCount\":5,\"size\":40,\"total\":166},\"errorCode\":0,\"errorMsg\":\"\"}"; + + let messageModel = messageModelMapper.map(JSONString: messageModelString); + return messageModel!; + } + + +} + +