【发布时间】:2020-01-31 03:45:12
【问题描述】:
我正在尝试在 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 core-data nsfetchrequest