Миграция базы данных на Swift- Coredata: Ошибка: (1) Ошибка ввода/вывода для базы данных и кода ошибки SQLite: 1, «Нет тIOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Миграция базы данных на Swift- Coredata: Ошибка: (1) Ошибка ввода/вывода для базы данных и кода ошибки SQLite: 1, «Нет т

Сообщение Anonymous »

Я разрабатываю приложение для iOS, используя SwiftData и сталкиваю проблемы с постоянными схемами базы данных. После обновления некоторых новых моделей я получаю ошибки coredata о пропущенных таблицах. < /P>
CoreData: error: (1) I/O error for database at SQLite error code:1, 'no such table: ZCARD'
< /code>
Это вся подсказка, просто продолжайте повторять одну и ту же ошибку < /p>
CoreData: error: (1) I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD'
CoreData: error: SQLCore dispatchRequest: exception handling request: , I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD' with userInfo of {
NSFilePath = "/Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store";
NSSQLiteErrorDomain = 1;
}
CoreData: error: -executeRequest: encountered exception = I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD' with userInfo = {
NSFilePath = "/Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store";
NSSQLiteErrorDomain = 1;
}
CoreData: error: (1) I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD'
CoreData: error: SQLCore dispatchRequest: exception handling request: , I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD' with userInfo of {
NSFilePath = "/Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store";
NSSQLiteErrorDomain = 1;
}
CoreData: error: -executeRequest: encountered exception = I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD' with userInfo = {
NSFilePath = "/Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store";
NSSQLiteErrorDomain = 1;
}
CoreData: error: (1) I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD'
CoreData: error: SQLCore dispatchRequest: exception handling request: , I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD' with userInfo of {
NSFilePath = "/Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store";
NSSQLiteErrorDomain = 1;
}
CoreData: error: -executeRequest: encountered exception = I/O error for database at /Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCARD' with userInfo = {
NSFilePath = "/Users/rick/Library/Developer/CoreSimulator/Devices/F307DA03-CEA2-406F-9CC7-5739B07DA25C/data/Containers/Data/Application/7C7794CF-FC99-4ACC-91EB-CD74AB65E94C/Library/Application Support/default.store";
NSSQLiteErrorDomain = 1;
}
< /code>
Я новичок в разработке iOS, и могу я спросить, какой правильный подход к обновлению схемы? Регистрация: все модели должным образом зарегистрированы в схеме < /li>
Управление версией: использование DatabasemigrationManager с отслеживанием версий < /li>
Удаление ручного файла: файлы Deleted Dataulate Paths < /li>
Clean Build: Chared xcode Build Folder и Devivel Data < /li>


let schema = Schema([
Card.self,
Category.self,
Reward.self,
RewardCategory.self,
Merchant.self,
PaymentRecord.self,
User.self,
RewardConversion.self,
])
< /code>
И я думаю, что мое самое большое изменение - удалить отношения между картой и пользователем < /p>
final class Card {
// Adding this Unique identifier for SwiftData to a new commit
@Attribute(.unique) var id: String

// ... some Fields

< /code>
@Model
final class User {
@Attribute(.unique) var id: String
var username: String
var email: String
var authProvider: AuthProvider
var appleUserID: String?
var googleUserID: String?
var profileImageData: Data?
var dateJoined: Date
var isCloudSyncEnabled: Bool
var achievements: [String] // Array of achievement IDs

// Temporarily removed the cards relationship to fix schema issues
// @Relationship(deleteRule: .cascade) var cards: [Card] = []

}
< /code>

After some debugging, I found that the issue is caused by my AuthenticationService but still I am not sure if it is because I changed my schema. Any help is much appreciated.
Settings.swift
import SwiftUI
import SwiftData

struct SettingsView: View {
@Environment(\.modelContext) private var modelContext
@Query private var cards: [Card]
@StateObject private var authService: AuthenticationService

init() {
// Initialize with a placeholder - will be properly set in onAppear
let tempContext = try! ModelContext(ModelContainer(for: User.self, RewardConversion.self))
_authService = StateObject(wrappedValue: AuthenticationService(modelContext: tempContext))
}

var body: some View {
NavigationView {
ZStack {
// Consistent background color
Color(.systemGroupedBackground)
.ignoresSafeArea()

ScrollView {
LazyVStack(spacing: 20) {

// Main Settings List
VStack(spacing: 0) {
// MARK: - Authentication Section
if !authService.isAuthenticated {
SettingsSection(title: "Account") {
VStack(spacing: 12) {
SignInButton(
provider: .apple,
isLoading: authService.isLoading
) {
authService.signInWithApple()
}

SignInButton(
provider: .google,
isLoading: authService.isLoading
) {
authService.signInWithGoogle()
}
}
.padding(.horizontal, 16)
}
} else {
SettingsSection(title: "Account") {
SettingsRow(
icon: "icloud.fill",
iconColor: .blue,
title: "iCloud Sync",
subtitle: authService.currentUser?.isCloudSyncEnabled == true ? "Enabled" : "Disabled"
) {
toggleCloudSync()
}

SettingsRow(
icon: "rectangle.portrait.and.arrow.right",
iconColor: .red,
title: "Sign Out",
subtitle: "Sign out from \(authService.currentUser?.authProvider.rawValue ?? "account")"
) {
authService.signOut()
}
}
}

// MARK: - App Info Section
SettingsSection(title: "App Info") {
SettingsRow(
icon: "info.circle.fill",
iconColor: .blue,
title: "Version",
subtitle: "1.0.0"
)
}
}
.padding(.horizontal, 16)
.padding(.bottom, 20)
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: { showNotificationCenter = true }) {
Image(systemName: "bell.fill")
.foregroundColor(.primary)
}
}
}
}
.navigationBarHidden(true)
.onAppear {
// Update the auth service with the proper model context
authService.updateModelContext(modelContext)
}
.alert("Error", isPresented: .constant(authService.errorMessage != nil)) {
Button("OK") {
authService.errorMessage = nil
}
} message: {
if let errorMessage = authService.errorMessage {
Text(errorMessage)
}
}
}

private func toggleCloudSync() {
guard let user = authService.currentUser else { return }
user.isCloudSyncEnabled.toggle()
try? modelContext.save()
}
}

#Preview {
SettingsView()
}
< /code>
UserProfileView.swift
import SwiftUI
import SwiftData

struct UserProfileView: View {
@Environment(\.modelContext) private var modelContext
@Query private var cards: [Card]
@StateObject private var authService: AuthenticationService
@State private var showingAchievements = false

init(authService: AuthenticationService) {
_authService = StateObject(wrappedValue: authService)
}

//...some code

private func checkAndUpdateAchievements() {
guard let user = authService.currentUser else { return }

let newAchievements = user.checkAchievements(with: cards)
if !newAchievements.isEmpty {
try? modelContext.save()
// Could show achievement notification here
}
}
}

#Preview {
UserProfileView(authService: AuthenticationService(modelContext: ModelContext(try! ModelContainer(for: User.self))))
}
< /code>
AuthenticationService.swift
import SwiftUI
import SwiftData
import AuthenticationServices
import Combine

@MainActor
final class AuthenticationService: ObservableObject {
@Published var isAuthenticated = false
@Published var currentUser: User?
@Published var isLoading = false
@Published var errorMessage: String?

private var modelContext: ModelContext

init(modelContext: ModelContext) {
self.modelContext = modelContext
checkAuthenticationStatus()
}

// MARK: - Model Context Management

func updateModelContext(_ newContext: ModelContext) {
self.modelContext = newContext
checkAuthenticationStatus()
}

// MARK: - Authentication Status

private func checkAuthenticationStatus() {
// Check if user is already signed in
if let userData = UserDefaults.standard.data(forKey: "currentUser"),
let user = try? JSONDecoder().decode(UserData.self, from: userData) {
loadUser(with: user.id)
}
}

private func loadUser(with id: String) {
let descriptor = FetchDescriptor(predicate: #Predicate { user in
user.appleUserID == id || user.googleUserID == id
})

if let user = try? modelContext.fetch(descriptor).first {
currentUser = user
isAuthenticated = true
}
}

// MARK: - Apple Sign In

func signInWithApple() {
isLoading = true
errorMessage = nil

let request = ASAuthorizationAppleIDProvider().createRequest()
request.requestedScopes = [.fullName, .email]

let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = AppleSignInCoordinator(authService: self)
authorizationController.presentationContextProvider = AppleSignInCoordinator(authService: self)
authorizationController.performRequests()
}

func handleAppleSignInResult(_ result: Result) {
isLoading = false

switch result {
case .success(let authorization):
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
handleAppleIDCredential(appleIDCredential)
}
case .failure(let error):
errorMessage = "Apple Sign In failed: \(error.localizedDescription)"
}
}

private func handleAppleIDCredential(_ credential: ASAuthorizationAppleIDCredential) {
let userID = credential.user
let email = credential.email ?? "[email protected]"
let fullName = credential.fullName
let username = [fullName?.givenName, fullName?.familyName]
.compactMap { $0 }
.joined(separator: " ")
.isEmpty ? "Apple User" : [fullName?.givenName, fullName?.familyName]
.compactMap { $0 }
.joined(separator: " ")

// Check if user already exists
let descriptor = FetchDescriptor(predicate: #Predicate { user in
user.appleUserID == userID
})

if let existingUser = try? modelContext.fetch(descriptor).first {
currentUser = existingUser
isAuthenticated = true
saveUserData(UserData(id: userID, provider: .apple))
} else {
// Create new user
let newUser = User(
username: username,
email: email,
authProvider: .apple,
appleUserID: userID
)

modelContext.insert(newUser)
try? modelContext.save()

currentUser = newUser
isAuthenticated = true
saveUserData(UserData(id: userID, provider: .apple))
}
}

// MARK: - Google Sign In

func signInWithGoogle() {
isLoading = true
errorMessage = nil

// TODO: Implement Google Sign In
// This would require Google Sign-In SDK
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.isLoading = false
self.errorMessage = "Google Sign In not yet implemented"
}
}

// MARK: - Sign Out

func signOut() {
currentUser = nil
isAuthenticated = false
UserDefaults.standard.removeObject(forKey: "currentUser")
}

// MARK: - Helper Methods

private func saveUserData(_ userData: UserData) {
if let data = try? JSONEncoder().encode(userData) {
UserDefaults.standard.set(data, forKey: "currentUser")
}
}
}

// MARK: - Supporting Types

private struct UserData: Codable {
let id: String
let provider: AuthProvider
}

// MARK: - Apple Sign In Coordinator

private class AppleSignInCoordinator: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
private let authService: AuthenticationService

init(authService: AuthenticationService) {
self.authService = authService
}

func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
authService.handleAppleSignInResult(.success(authorization))
}

func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
authService.handleAppleSignInResult(.failure(error))
}

func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first else {
return UIWindow()
}
return window
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... se-and-sql
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»