Click here to load reader

Webinar - Developing with Couchbase Lite iOS

  • View
    1.786

  • Download
    4

Embed Size (px)

DESCRIPTION

Learn how to develop with Couchbase Lite for iOS in this technical lecture led by Jens Alfke, lead Couchbase Lite iOS developer. Walkthrough developing your first iOS application using Native APIs, and hear about what is to come for Couchbase Lite iOS. In this webinar you will see: An overview of the Couchbase Lite iOS API A step-by-step demonstration on how to develop a iOS application with Couchbase Lite A quick demo of a iOS app An explanation of the future plans for Couchbase Lite iOS

Text of Webinar - Developing with Couchbase Lite iOS

2. TellThemWhatYoureGoingToTellThem InstallaFonandsetupwalk-through DemoofGrocerySyncsampleapp TourofGrocerySynccode withdigressionsabouttheAPI andthedocumentmodel andquerying BeyondGrocerySync 3. GeNngUpAndRunning DownloadCouchbaseLite DownloadGrocerySyncsamplecode Copyframeworkintosampleappfolder Build&Run 4. 1.DownloadCouchbaseLitewww.couchbase.com/communi:es/couchbase-lite 5. DownloadGrocerySyncgithub.com/couchbaselabs/Grocery-Sync-iOS 6. PlugInTheFramework option 7. LiveDemo 8. ATouroftheCode andtheAPI 9. Ini;aliza;onDemoAppDelegate.m:64 // Initialize Couchbase Lite and find/create my database: NSError* error; self.database = [[CBLManager sharedInstance] createDatabaseNamed: kDatabaseName error: &error]; if (!self.database) [self showAlert: @"Couldn't open database" error: error fatal: YES]; 10. Manager,Databases,Documents CBLManager!CBLDatabaseDatabase CBLDocumentdoc1 db otherdb {}text: Vacuum, created: 2013-10-08, check: falseDocument doc1 CBLDocument doc2 CBLDocument doc3thumb.jpg 11. Manager Collec;onofnameddatabases Generallyasingleton Unlessyourunonmul:plethreads Managesdatabasestorage(localdirectory) 12. Database Namespacefordocuments Containsviewsandtheirindexes Containsvalida;onfunc;ons Sourceandtargetofreplica;on 13. Document HasuniqueIDwithinitsdatabase Containsarbitrary*JSONobject *exceptkeysthatstartwith_arereserved Thereisnoexplicit,enforcedschema Denormaliza:onisOKusearraysordic:onaries MaycontainbinaryaVachments Datablobs,canbelarge,taggedwithMIMEtype Versioned Mul:-VersionConcurrencyControl(MVCC) EveryupdatecreatesarevisionID(basedondigestofcontents) RevisionIDhistoryisstored 14. Ini;aliza;onDemoAppDelegate.m:64 // Initialize Couchbase Lite and find/create my database: NSError* error; self.database = [[CBLManager sharedInstance] createDatabaseNamed: kDatabaseName error: &error]; if (!self.database) [self showAlert: @"Couldn't open database" error: error fatal: YES]; 15. Crea;ngaDatabaseView RootViewController.m:101Not a U IView a datab ase view is like a n index. // Define a view with a map function that indexes to-do items by creation date: [[theDatabase viewNamed: @"byDate"] setMapBlock: MAPBLOCK({ id date = doc[@"created_at"]; if (date) emit(date, doc); }) reduceBlock: nil version: @"1.1"]; 16. Views&Queries CBLDatabase dbfunction(doc) { emit(doc.created, doc.title); } map fu nctionCBLView View completed byDatekeyvaluedocID2013-03-12taxesdoc172013-09-30callmomdoc622013-10-17catfooddoc822013-10-17teabagsdoc832013-10-22upgradedoc90view index}CBLQuery 17. Views Map/Reducemechanism PopularinotherNoSQLdatabases Aviewissimilartoindexinrela:onaldatabase. App-denedmapfunc;on Calledoneverydocument Canemitarbitrarykey/valuepairsintotheindex Op;onalreducefunc;on Dataaggrega:on/grouping Func;onsareregisteredasna;veblocks/callbacks NotstoredasJavaScriptindesigndocument(asinCouchDB) 18. Crea;ngaDatabaseView RootViewController.m:101Not a U IView a datab ase view is like a n index. // Define a view with a map function that indexes to-do items by creation date: [[theDatabase viewNamed: @"byDate"] setMapBlock: MAPBLOCK({ id date = doc[@"created_at"]; if (date) emit(date, doc); }) reduceBlock: nil version: @"1.1"]; 19. DrivingtheTablefromaViewQuery RootViewController.m:101 // Create a query sorted by descending date, i.e. newest items first: CBLLiveQuery* query = [[[database viewNamed:@"byDate"] query] asLiveQuery]; query.descending = YES; ! // Plug the query into the CBLUITableSource, which will use it to drive the table. // (The CBLUITableSource uses KVO to observe the query's .rows property.) self.dataSource.query = query; self.dataSource.labelProperty = @"text";RootViewController.h:41 @property(nonatomic, strong) IBOutlet UITableView *tableView; @property(nonatomic, strong) IBOutlet CBLUITableSource* dataSource; 20. Queries Basicfeatureset Keyranges,oset/limit,reverse,groupbykey Nojoinsorfancysor:ng butcompoundkeys(andcleveremits)allowforsometricks LiveQuerysubclass Monitorsdatabase,pushesno:ca:ons UsesKVOoniOS,candriveaUITableView Upcominggoodies! Full-textindexing Geo(bounding-box)queries 21. LiveQueries&TableDataSourceskeyvalue2013-09-30Pencilshavings doc622013-10-17Mangosdoc822013-10-17seconddoc83view indexdocID}CBLQuery CBLLiveQueryCBLUI- TableSourcedata source 22. DrivingtheTablefromaViewQuery RootViewController.m:101 // Create a query sorted by descending date, i.e. newest items first: CBLLiveQuery* query = [[[database viewNamed:@"byDate"] query] asLiveQuery]; query.descending = YES; ! // Plug the query into the CBLUITableSource, which will use it to drive the table. // (The CBLUITableSource uses KVO to observe the query's .rows property.) self.dataSource.query = query; self.dataSource.labelProperty = @"text";RootViewController.h:41 @property(nonatomic, strong) IBOutlet UITableView *tableView; @property(nonatomic, strong) IBOutlet CBLUITableSource* dataSource; 23. WiringUpTheTableView RootViewController.xib 24. DisplayingTableCells DemoAppDelegate.m:131- (void)couchTableSource:(CBLUITableSource*)source willUseCell:(UITableViewCell*)cell forRow:(CBLQueryRow*)row { // Set the cell background and font: // Configure the cell contents. Map function (above) copies the doc properties // into its value, so we can read them without having to load the document. NSDictionary* rowValue = row.value; BOOL checked = [rowValue[@"check"] boolValue]; if (checked) { cell.textLabel.textColor = [UIColor grayColor]; cell.imageView.image = [UIImage imageNamed:@"checked"]; } else { cell.textLabel.textColor = [UIColor blackColor]; cell.imageView.image = [UIImage imageNamed: @"unchecked"]; } // cell.textLabel.text is already set, thanks to setting up labelProperty } 25. RespondingToTaps DemoAppDelegate.m:131- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Ask CBLUITableSource for the corresponding query row, and get its document: CBLQueryRow *row = [self.dataSource rowAtIndex:indexPath.row]; CBLDocument *doc = row.document; ! // Toggle the document's 'checked' property: NSMutableDictionary *docContent = [doc.properties mutableCopy]; BOOL wasChecked = [docContent[@"check"] boolValue]; docContent[@"check"] = @(!wasChecked); ! // Save changes: NSError* error; if (![doc.currentRevision putProperties: docContent error: &error]) { [self showErrorAlert: @"Failed to update item" forError: error]; } } 26. AddingNewItems DemoAppDelegate.m:247-(void)textFieldDidEndEditing:(UITextField *)textField { // Get the name of the item from the text field: NSString *text = addItemTextField.text; if (text.length == 0) { return; } addItemTextField.text = nil; ! // Create the new document's properties: NSDictionary *inDocument = @{ @"text": text, @"check": @NO, @"created_at": [CBLJSON JSONObjectWithDate: [NSDate date]] }; // Save the document: CBLDocument* doc = [database untitledDocument]; NSError* error; if (![doc putProperties: inDocument error: &error]) { [self showErrorAlert: @"Couldn't save new item" forError: error]; 27. Dele;ngItemsDemoAppDelegate.m:191- (NSArray*)checkedDocuments { NSMutableArray* checked = [NSMutableArray array]; for (CBLQueryRow* row in self.dataSource.rows) { CBLDocument* doc = row.document; if ([doc[@"check"] boolValue]) [checked addObject: doc]; } return checked; } ! !- (void)deleteCheckedDocuments { NSError* error; if (![dataSource deleteDocuments: self.checkedDocuments error: &error]) { [self showErrorAlert: @"Failed to delete items" forError: error]; } } 28. OK,ButWheresTheSync? 29. Crea;ngReplica;ons DemoAppDelegate.m:291 // Tell the database to use this URL for bidirectional sync. // This call returns an array of the pull and push replication objects: NSArray* repls = [self.database replicateWithURL: newRemoteURL exclusively: YES]; if (repls) { _pull = repls[0]; _push = repls[1]; _pull.continuous = _push.continuous = YES; // Observe replication progress changes, in both directions: NSNotificationCenter* nctr = [NSNotificationCenter defaultCenter]; [nctr addObserver: self selector: @selector(replicationProgress:) name: kCBLReplicationChangeNotification object: _pull]; [nctr addObserver: self selector: @selector(replicationProgress:) name: kCBLReplicationChangeNotification object: _push]; } 30. Replica;on Database dbDir: push Remote:hkp://server/db Auth: Replica;onReplica;onDir: pull Remote:hkp://server/db Auth: ns tio icatif no 31. Replica;on EachReplica;onisone-direc;onal(pushorpull) Replica;onscanbeone-shot,con;nuousorpersistent One-shot:Stopswhencomplete. Con:nuous:Keepsmonitoringchanges:llappquits Persistent:Automa:callystartsagainonnextrelaunch Replicatorrunsinabackgroundthread Itdetectsonline/oine,handlesconnec:onerrors,retries Youjustseedocument-changedorquery-changedno:ca:ons. ProgressisobservablethroughKVOorNSNo;ca;on 32. MonitoringReplica;ons DemoAppDelegate.m:353// Called in response to replication-change notifications. Updates the progress UI. - (void) replicationProgress: (NSNotificationCenter*)n { if (_pull.mode== kCBLReplicationActive || _push.mode== kCBLReplicationActive) { // Sync is active -- aggregate progress of both replications: unsigned completed = _pull.completed + _push.completed;

Search related