AWS AppSync iOS离线模式报错:Variable id未提供,无法获取已存记录
Hey there, let's break down and fix your AWS AppSync offline functionality issues step by step:
First, let's pinpoint the root causes of your two main issues: the missing id variable error during offline saves, and not being able to retrieve offline-stored records.
1. Fix the "Variable id was not provided" Error
This error happens because AppSync's offline cache relies on explicit query variables to locate and modify cached data. Looking at your code:
- The
transaction?.read(query: query)line uses an undefinedqueryvariable, which likely isn't passing the requiredidparameter. - When updating the cache in
transaction?.update, you need to ensure the query you're targeting includes the exactidvariable that matches your user.
Fix:
Replace the vague query with an explicit, parameterized query:
// Define the query with the correct user ID first let getUserCategoriesQuery = GetUserCategoriesOfUserQuery(id: userObjInput.id!) let selectionSets = try transaction?.read(query: getUserCategoriesQuery) // Use the same parameterized query for the update operation try transaction?.update(query: getUserCategoriesQuery) { (data: inout GetUserCategoriesOfUserQuery.Data) in // Rest of your update logic here }
2. Fix Offline Record Retrieval
Your current code uses unnecessary optional chaining when building the category object for the cache, which can prevent data from being properly written to the offline store. Additionally, you should handle cases where the existing category array is nil.
Fix:
Clean up the object initialization and ensure the cache array is properly managed:
try transaction?.update(query: getUserCategoriesQuery) { (data: inout GetUserCategoriesOfUserQuery.Data) in // Initialize an empty array if existing categories are nil var existingCategories = data.getAllCategoriesForUser ?? [] // Create the new category object WITHOUT optional chain wrappers let newCategory = GetUserCategoriesOfUserQuery.Data.GetAllCategoriesForUser( id: UUID().uuidString, categoryName: CategoryInputs.categoryName!, isDeleted: false, user: GetUserCategoriesOfUserQuery.Data.GetAllCategoriesForUser.User( id: userObjInput.id!, firstName: userObjInput.firstName!, lastName: userObjInput.lastName! ) ) existingCategories.append(newCategory) data.getAllCategoriesForUser = existingCategories }
3. Bonus: Avoid Cache Conflicts (Optional but Recommended)
You're using a hardcoded id: "id" for your user object, which can cause cache collisions. Instead, generate a unique ID for each user:
let uniqueUserId = UUID().uuidString let userObjInput = userObjectInput(id: uniqueUserId, firstName: "firstname", lastName: "lastName")
4. Verify Offline Configuration
Double-check that your AppSync client is initialized with offline support enabled:
guard let config = AWSAppSyncServiceConfig() else { fatalError("Failed to load AppSync config") } let offlineDBURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("appsync-offline.db") let appSyncConfig = try AWSAppSyncClientConfiguration( appSyncServiceConfig: config, databaseURL: offlineDBURL ) appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
After applying these changes, your offline mutations should save correctly without the id variable error, and you'll be able to retrieve the cached records when offline.
内容的提问来源于stack exchange,提问作者Chandra Sekhar

