将数据传递到 Swift 中的 ViewModel

问题描述 投票:0回答:1

我对 SwiftUI 和在 XCode 上开发应用程序相当陌生。我对其他语言有很好的经验,但我很难理解一些事情。

基本上我有一个 ViewModel 设置为 API,用于从我的服务器提取通知,如下所示:

import Foundation
import SwiftUI


class NotificationsAPI: ObservableObject {
    @Published var notifications: [KXNotification] = []

    let userId = [something here]
    
    func fetch() {
        guard let url = URL(string: "xxxxxx.php?id=userId") else {
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in guard let data = data, error == nil else {
                return
        }
            
        //Convert to JSON
            do {
                let notifications = try JSONDecoder().decode([KXNotification].self, from: data)
                DispatchQueue.main.async {
                    self?.notifications = notifications
                }
            } catch {
                print(error)
            }
        }
        
        task.resume()
    }
}
   

在我的主视图上,我有以下内容,但我需要将“userId”传递到该视图上的NotificationsAPI视图模型,以便它从服务器带来正确的通知。

import SwiftUI

struct NotificationsView: View {
    @StateObject var viewModel = NotificationsAPI()
    
    var body: some View {
        VStack(alignment: .center, spacing: 16) {
            VStack(alignment: .leading, spacing: 8) {
                HStack(alignment: .bottom, spacing: 0) {
                    Text("Notifications")
                        .font(.poppins(size: 20, weight: .medium))
                    
                    Spacer(minLength: 0)
                    
                    Text("View All")
                        .font(.poppins(size: 15, weight: .medium))
                        .themeForegroundColor(\.gray2)
                        .onTapNavigate(to: AllExercisesView())
                }
                
                Text("Notifications: \(viewModel.notifications.count)")
                    .font(.openSans(size: 12, weight: .regular))
            }
            
            VStack(alignment: .center, spacing: 16) {
                ForEach(viewModel.notifications, id: \.self) { notification in
                    LongCardView(
                        image: .web(link: notification.notificationImage),
                        title: notification.notificationTitle,
                        subTitle: notification.notificationDate,
                        icon: "i_icon"
                    )
                }
            }
            .onAppear {
                viewModel.fetch()
            }
        }
    }
}
        

提前致谢。

我尝试了很多方法,但都很难让它发挥作用。非常感谢一些建议。

swift swiftui viewmodel
1个回答
0
投票

您有几个选择。

  1. 您可以将参数传递给 fetch() 方法。所以它看起来像

    func fetch(userId: String(or whatever type you have)
    。 您可以在文档中了解函数中的参数如何工作:https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/

  2. 作为第二个选项,您可以使用 userId 初始化 viewModel。您可以在文档中阅读有关初始化的信息:https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization。或者让chatGPT为您添加

第一个选项更容易且更可取

© www.soinside.com 2019 - 2024. All rights reserved.