【问题标题】:Mapping a single response object with SwiftUI and MVVM pattern使用 SwiftUI 和 MVVM 模式映射单个响应对象
【发布时间】:2020-07-21 07:55:33
【问题描述】:

我有一个简单的用户配置文件模型,它作为单个节点从 JSON API 返回。

(模型)UserProfile.swift

struct UserProfile: Codable, Identifiable {
    let id: Int
    var name: String
    var profile: String
    var image: String?
    var status: String
    var timezone: String
}

(服务)UserProfileService.swift

class UserProfileService {    
    func getProfile(completion: @escaping(UserProfile?) -> ()) {
        guard let url = URL(string: "https://myapi.com/profile") else {
            completion(nil)
            return
        }
        
        var request = URLRequest(url: url)
        
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.httpMethod = "GET"
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                DispatchQueue.main.async {
                    completion(nil)
                }
                return
            }
            
            do {
                let profile = try JSONDecoder().decode(UserProfile.self, from: data)
                
                DispatchQueue.main.async {
                    completion(profile)
                }
            } catch {
                print("ERROR: ", error)
            }
        }.resume()
    }
}

(查看模型)UserProfileViewModel.swift

class UserProfileRequestViewModel: ObservableObject {
    @Published var profile = UserProfile.self
    
    init() {
        fetchProfile()
    }
    
    func fetchProfile() {
        UserProfileService().getProfile { profile in
            if let profile = profile {
                self.profile = UserProfileViewModel.init(profile: profile)
            }
        }
    }
}

class UserProfileViewModel {
    var profile: UserProfile
    
    init(profile: UserProfile) {
        self.profile = profile
    }
    
    var id: Int {
        return self.profile.id
    }
}

有人可以告诉我需要在上面输入什么self.profile = UserProfileViewModel.init(profile: profile),因为这会导致错误“无法将'UserProfileViewModel'类型的值分配给'UserProfile.Type'”? p>

如果我有一个数据循环,那么像下面这样循环不会有问题,但是如何处理单个节点?

if let videos = videos {
    self.videos = videos.map(VideoViewModel.init)
}

【问题讨论】:

    标签: mvvm swiftui


    【解决方案1】:

    似乎您的 UserProfileService().getProfile 已经返回 UserProfile 类型,所以您可能需要

    UserProfileService().getProfile { profile in
       if let profile = profile {
          self.profile = profile
       }
    }
    

    @Published var profile : UserProfile?
    

    【讨论】:

    • 谢谢,是的,这正是我所需要的。虽然我不明白“if let profile = profile { ... }?那只是检查没有空响应吗?
    • 是的。 UserProfileService 可以通过我们检查的“if let profile”返回 nil“completion(nil)”。你还需要在你的catch部分返回completion(nil)(以防你在jsondecode中有错误)
    【解决方案2】:

    具有正确视图模型的工作版本,因此为可能有相同问题的其他人添加此版本!

    (查看模型)UserProfileViewModel.swift

    class UserProfileViewModel: ObservableObject {
        @Published var profile: UserProfile?
        
        init() {
            fetchProfile()
        }
        
        func fetchProfile() {
            UserProfileService().getProfile { profile in
                  self.profile = profile
               
            }
        }
        
        var name: String {
            return self.profile?.name ?? "Name"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2021-12-03
      • 2011-11-25
      • 2020-04-24
      • 2012-01-17
      • 1970-01-01
      相关资源
      最近更新 更多