在 SwiftUI 视图模型中使用 FetchRequest

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

我尝试在 SwiftUI 中遵循 MVVM 模式,但遇到了核心数据和获取请求的问题。

我看过的所有视频和读过的文章在视图中都有一个@FetchRequest,用于访问和修改核心数据。

如何将其放入 SettingsVCModel 中?我似乎无法弄清楚,因此我将获取请求保留在视图结构(SettingsVC)内并在那里使用它。

但是到目前为止,这都是通过按钮来执行操作的。现在我需要使用一个切换按钮来完成此操作,该切换按钮只有一个与之关联的绑定变量,并且没有像按钮那样的操作。

我在 SettingsVCModel 内的 @Published bio 上尝试了 didSet 方法,但是您无权访问获取请求。

我正在使用的代码如下:

struct SettingsVC: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: UserSettings.getUserSettings()) var userSettings : FetchedResults<UserSettings>
    @ObservedObject var model = SettingsVCModel()
    
    var body: some View {
        NavigationView {
            Form{
                Section(header: Text("Application")){
                    Toggle(isOn: $model.bio, label: {Text(model.determineBiometricType())})
                    Picker(selection: $model.unitSelection, label: Text("Units")) {
                        Text("Imperial").tag(0)
                        Text("Metric").tag(1)
                    }
                    SettingsButton(toggleButton: $model.openSettings, title: "System Authorizations")
                }
                Section(header: Text("Feedback")){
                    NavigationLink(destination: ContactVC()){
                        Text("Contact Me")
                    }
                    SettingsButton(toggleButton: $model.rateApp, title: "Please Rate Body Insights")
                    SettingsButton(toggleButton: $model.tellAFriend, title: "Tell a Friend")
                }
                Section(header: Text("General")){
                    NavigationLink(destination: AboutVC()){
                        Text("About")
                    }
                    SettingsButton(toggleButton: $model.openPrivacyPolicy, title: "Privacy Policy", openPrivacyPolicy: true)
                }
            }
            .onAppear{
                self.model.bio = self.userSettings.first!.useBiometricUnlock
                self.model.unitSelection = self.userSettings.first!.usesMetric ? 1 : 0
            }
            .navigationBarTitle("Settings")
            .sheet(isPresented: $model.tellAFriend, content: {
                ShareSheetView(activityItems: ["Hey, check out this cool app! https://apps.apple.com/uy/app/body-insights/id1397531585"])
            })
            
        }
    }
} 


final class SettingsVCModel : ObservableObject{
    @Published var unitSelection = 0
    @Published var tellAFriend = false
    @Published var openPrivacyPolicy = false
    @Published var bio = false
    @Published var openSettings = false {
        didSet{
            if openSettings{
                openAppSettingsApp()
                openSettings = false
            }
        }
    }
    @Published var rateApp = false {
        didSet{
            if rateApp{
                openRateApp()
                rateApp = false
            }
        }
    }
    
    func openRateApp() {
        let appID = "1397531585"
        let urlString = "https://itunes.apple.com/us/app/appName/id\(appID)?mt=8&action=write-review"
        let url = URL(string: urlString)!
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    
    func openAppSettingsApp() {
        guard
            let settingsURL = URL(string: UIApplication.openSettingsURLString),
            UIApplication.shared.canOpenURL(settingsURL)
            else {
                return
        }
        
        UIApplication.shared.open(settingsURL)
        return
    }
    
    func determineBiometricType() -> String {
        let authContext = LAContext()
        let _ = authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
        switch(authContext.biometryType) {
        case .none:
            return "Not Avaliable"
        case .touchID:
            return "TouchID"
        case .faceID:
            return "FaceID"
        @unknown default:
            return "Not Avaliable"
        }
    }
}
 
public class UserSettings : NSManagedObject, Identifiable {
    @NSManaged public var useBiometricUnlock : Bool
    @NSManaged public var usesMetric : Bool
    @NSManaged public var name : String
    @NSManaged public var birthday : Date
    @NSManaged public var age : Int
    
    static func getUserSettings() -> NSFetchRequest<UserSettings> {
        let request : NSFetchRequest<UserSettings> = UserSettings.fetchRequest() as! NSFetchRequest<UserSettings>
        request.sortDescriptors = []
        return request
    }
    
    static func save(){
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        do {
            try context.save()
        } catch{
            print(error)
        }
    }
    
    static func preloadData(){
        let preloadKey: String  = "preloadKey"
        let isPreloaded = UserDefaults.standard.bool(forKey: preloadKey)
        
        if !isPreloaded {
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            let defaultSettings = UserSettings(context: context)
            let deviceName = UIDevice.current.name
            let firstName = deviceName.components(separatedBy: " ").first
            let isMetric = NSLocale.current.usesMetricSystem

            defaultSettings.name = firstName ?? ""
            defaultSettings.useBiometricUnlock = false
            defaultSettings.usesMetric = isMetric
            defaultSettings.age = 0
            defaultSettings.birthday = Date()

            UserDefaults.standard.set(true, forKey: preloadKey)
            UserSettings.save()
        }
    }
}
 
swift swiftui core-data nsfetchrequest
3个回答
19
投票

看来你只能在视图中使用 SwiftUI 的

FetchRequest
。 如果您检查其定义,FetchRequest 符合
DynamicProperty
,并且如果您阅读有关两者的文档,它们意味着它被设计为在 SwiftUI 视图中使用。

获取请求:

/// Property wrapper to help Core Data clients drive views from the results of
/// a fetch request. The managed object context used by the fetch request and
/// its results is provided by @Environment(\.managedObjectContext).
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct FetchRequest<Result> : DynamicProperty where Result : NSFetchRequestResult {

动态属性:

/// Represents a stored variable in a `View` type that is dynamically
/// updated from some external property of the view. These variables
/// will be given valid values immediately before `body()` is called.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicProperty {

    /// Called immediately before the view's body() function is
    /// executed, after updating the values of any dynamic properties
    /// stored in `self`.
    mutating func update()
}

0
投票

我最终放弃了

EnvironmentObject
的想法,并使用围绕核心数据存储的单例协议的包装服务。 如果您仍然想保留 MVVM 原则,我认为没有其他选择可以这样做。


0
投票

CoreData 可以被认为是 ViewModel 本身。我们在视图中使用 @FetchRequest 来“观察”CoreData 描述的模型发生的变化。如果您还将 CloudKit 与 CoreData 一起使用,那么当您的视图处于活动状态时,您的 @FetchRequest 也处于活动状态,并且来自 iCloud 的任何入站更改都将被“观察到”,并将导致您的视图更新。

如果您想从您自己构建的 ViewModel 中的 CoreData 获取数据,只需使用非 SwiftUI 函数即可。我今天刚刚在 ViewModel 中写了这个:

let request = API.fetchRequest()
let sort = NSSortDescriptor(keyPath: \API.priority, ascending: true)
request.sortDescriptors = [sort]
do {
  if let apis = try container.viewContext.fetch(request) as? [API] {
    logger.debug("APIs fetched: \(apis.count)")
    self.apis = apis
  }
} catch {
  logger.debug("Fetch failed 😭")
}

就像这样,我将数据提取到我的 ViewModel 中,现在我可以将其分配给一些 @Published 属性。快乐编码!

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