Objective-C API examples
We can use JSONStore for MobileFirst applications.
The following sections contain example implementations for iOS devices with JSONStore APIs. Other helpful topics include:
- JSONStore overview - Learn about key concepts.
- Enable JSONStore - Learn how to enable JSONStore in different environments.
- JSONStore API concepts - Learn about general information about the APIs that apply to all implementations of the JSONStore API.
- JSONStore troubleshooting - Learn how to debug and understand possible errors.
- JSONStore advanced topics - Learn about security, multiple user support, performance, and concurrency.
- JSONStore Class Reference - Learn about JSONStore APIs for Objective-C.
- Work with external data - Explains how to get data from an external source and send changes back to the external source.
Initialize and open connections, get an Accessor, and add data
// Create the collections object that will be initialized. JSONStoreCollection* people = [[JSONStoreCollection alloc] initWithName:@"people"]; [people setSearchField:@"name" withType:JSONStore_String]; [people setSearchField:@"age" withType:JSONStore_Integer]; // Optional options object. JSONStoreOpenOptions* options = [JSONStoreOpenOptions new]; [options setUsername:@"carlos"]; //Optional username, default 'jsonstore' [options setPassword:@"123"]; //Optional password, default no password // This object will point to an error if one occurs. NSError* error = nil; // Open the collections. [[JSONStore sharedInstance] openCollections:@[people] withOptions:options error:&error]; // Add data to the collection NSArray* data = @[ @{@"name" : @"carlos", @"age": @10} ]; int newDocsAdded = [[people addData:data andMarkDirty:YES withOptions:nil error:&error] intValue];
Initialize with a secure random token from the server
[WLSecurityUtils getRandomStringFromServerWithBytes:32 timeout:1000 completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // You might want to see the response and the connection error // before moving forward. // Get the secure random string using the data that is // returned from the generator on the server. NSString* secureRandom = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; JSONStoreCollection* ppl = [[JSONStoreCollection alloc] initWithName:@"people"]; [ppl setSearchField:@"name" withType:JSONStore_String]; [ppl setSearchField:@"age" withType:JSONStore_Integer]; // Optional options object. JSONStoreOptions* options = [JSONStoreOptions new]; [options setUsername:@"carlos"]; //Optional username, default 'jsonstore' [options setPassword:@"123"]; //Optional password, default no password [options setSecureRandom:secureRandom]; //Optional, default one will be generated locally // This points to an error if one occurs. NSError* error = nil; [[JSONStore sharedInstance] openCollections:@[ppl] withOptions:options error:&error]; // Other JSONStore operations (e.g. add, remove, replace, etc.) go here. }];
Find - locate documents inside the Store
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // Add additional find options (optional). JSONStoreQueryOptions* options = [JSONStoreQueryOptions new]; [options setLimit:@10]; // Returns a maximum of 10 documents, default no limit. [options setOffset:@0]; // Skip 0 documents, default no offset. // Search fields to return, default: ['_id', 'json']. [options filterSearchField:@"_id"]; [options filterSearchField:@"json"]; // How to sort the returned values , default no sort. [options sortBySearchFieldAscending:@"name"]; [options sortBySearchFieldDescending:@"age"]; // Find all documents that match the query part. JSONStoreQueryPart* queryPart1 = [[JSONStoreQueryPart alloc] init]; [queryPart1 searchField:@"name" equal:@"carlos"]; [queryPart1 searchField:@"age" lessOrEqualThan:@10]; NSArray* results = [people findWithQueryParts:@[queryPart1] andOptions:options error:&error]; // results = @[ @{@"_id" : @1, @"json" : @{ @"name": @"carlos", @"age" : @10}} ]; for (NSDictionary* result in results) { NSString* name = [result valueForKeyPath:@"json.name"]; // carlos. int age = [[result valueForKeyPath:@"json.age"] intValue]; // 10 NSLog(@"Name: %@, Age: %d", name, age); }
Replace - change the documents already stored inside a Collection
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // Find all documents that match the queries. NSArray* docs = @[ @{@"_id" : @1, @"json" : @{ @"name": @"carlitos", @"age" : @99}} ]; // This object will point to an error if one occurs. NSError* error = nil; // Perform the replacement. int docsReplaced = [[people replaceDocuments:docs andMarkDirty:NO error:&error] intValue];
Remove - delete all documents that match the query
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // Find document with _id equal to 1 and remove it. int docsRemoved = [[people removeWithIds:@[@1] andMarkDirty:NO error:&error] intValue];
Count - gets the total number of documents that match a query
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // Count all documents that match the query. // The default query is @{} which will // count every document in the collection. JSONStoreQueryPart *queryPart = [[JSONStoreQueryPart alloc] init]; [queryPart searchField:@"name" equal:@"carlos"]; // This object will point to an error if one occurs. NSError* error = nil; // Perform the count. int countResult = [[people countWithQueryParts:@[queryPart] error:&error] intValue];
Destroy - wipes data for all users, destroys the internal storage, and clears security artifacts
// This object will point to an error if one occurs. NSError* error = nil; // Perform the destroy. [[JSONStore sharedInstance] destroyDataAndReturnError:&error];
Security - close access to all opened Collections for the current user
// This object will point to an error if one occurs. NSError* error = nil; // Close access to all collections in the store. [[JSONStore sharedInstance] closeAllCollectionsAndReturnError:&error];
Security - change the password used to access a Store
// The password should be user input. // It is hardcoded in the example for brevity. NSString* oldPassword = @"123"; NSString* newPassword = @"456"; NSString* username = @"carlos"; // This object will point to an error if one occurs. NSError* error = nil; // Perform the change password operation. [[JSONStore sharedInstance] changeCurrentPassword:oldPassword withNewPassword:newPassword forUsername:username error:&error]; // Remove the passwords from memory. oldPassword = nil; newPassword = nil;
Push - get all documents that are marked as dirty, send them to a MobileFirst adapter, and mark them clean
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs NSError* error = nil; // Return all documents marked dirty NSArray* dirtyDocs = [people allDirtyAndReturnError:&error]; // ACTION REQUIRED: Handle the dirty documents here // (e.g. send them to a MobileFirst Adapter). // Mark dirty documents as clean int numCleaned = [[people markDocumentsClean:dirtyDocs error:&error] intValue];
Pull - get new data from a MobileFirst adapter
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // ACTION REQUIRED: Get data (e.g. MobileFirst Adapter). // For this example, it is hardcoded. NSArray* data = @[ @{@"id" : @1, @"ssn": @"111-22-3333", @"name": @"carlos"} ]; int numChanged = [[people changeData:data withReplaceCriteria:@[@"id", @"ssn"] addNew:YES markDirty:NO error:&error] intValue];
Check whether a document is dirty
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // Check if document with _id '1' is dirty. BOOL isDirtyResult = [people isDirtyWithDocumentId:1 error:&error];
Check the number of dirty documents
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // Check if document with _id '1' is dirty. int dirtyDocsCount = [[people countAllDirtyDocumentsWithError:&error] intValue];
Remove a Collection
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // Remove the collection. [people removeCollectionWithError:&error];
Clear all data that is inside a Collection
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // This object will point to an error if one occurs. NSError* error = nil; // Remove the collection. [people clearCollectionWithError:&error];
Start a transaction, add some data, remove a document, commit the transaction and roll back the transaction if there is a failure
// Get the accessor to an already initialized collection. JSONStoreCollection* people = [[JSONStore sharedInstance] getCollectionWithName:@"people"]; // These objects will point to errors if they occur. NSError* error = nil; NSError* addError = nil; NSError* removeError = nil; // We can call every JSONStore API method inside a transaction except: // open, destroy, removeCollection and closeAll. [[JSONStore sharedInstance] startTransactionAndReturnError:&error]; [people addData:@[ @{@"name" : @"carlos"} ] andMarkDirty:NO withOptions:nil error:&addError]; [people removeWithIds:@[@1] andMarkDirty:NO error:&removeError]; if (addError != nil || removeError != nil) { // Return the store to the state before start transaction was called. [[JSONStore sharedInstance] rollbackTransactionAndReturnError:&error]; } else { // Commit the transaction thus ensuring atomicity. [[JSONStore sharedInstance] commitTransactionAndReturnError:&error]; }
Get file information
// This object will point to an error if one occurs NSError* error = nil; // Returns information about files JSONStore uses to persist data. NSArray* results = [[JSONStore sharedInstance] fileInfoAndReturnError:&error]; // => [{@"isEncrypted" : @(true), @"name" : @"carlos", @"size" : @3072}]
Parent topic: JSONStore examples