{"_id":"5fa193e2dec8660049cc536a","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Migration guide from 2.x to 3.x","type":"basic","slug":"migration-guide-from-2x-to-3x","excerpt":"","body":"Migration guide from 2.x to 3.x\n\n### MOCA.h API changes\n\nChanged methods:\n\n- `[MOCA version]`;\n\nHas changed to:\n\n`MOCA.sdKVersion;`\n\n--------\n\n- `+(void) trackViewed:(NSString*) itemId belongingTo:(NSString*)category withReco:(BOOL)recommended;`\n\nHas changed to:\n\n- `+ (void)trackViewed:(NSString *)itemId belongingTo:(NSString *)category wasRecommended:(BOOL)recommended;`\n\n--------\n\nThe following accessors are now properties instead of method calls.\n\n`appKey`\n`appSecret`\n`config`\n\n(e.g (Objective-C) Use `MOCA.appKey` instead of [MOCA appKey])\n\n--------\n\nThe following methods have been removed:\n\n```\n+(CLLocation*) getLastKnownLocation;\n\n//UILocalNotification no longer supported\n\n+(void)handleLocalNotification:(UILocalNotification *)notification;\n\n+(BOOL)isMocaLocalNotification:(UILocalNotification *)notification;\n\n+(BOOL)handleActionWithIdentifier:(NSString *)identifier\n             forLocalNotification:(UILocalNotification *)notification;\n\n```\n--------\n\n### Event and action listener changes\n\nThe `MOCAProximityEventsDelegate` protocol has been removed. \n\nUse the following methods instead. [Location Events Listener](doc:location-events-listener) \n\n```\n/**\n * Adds a new observer for Region Events (RegionGroups, Places, Zones, Beacons)\n * Compatible protocols\n *  RegionEventsObserver\n *  RegionGroupEventsObserver\n *  PlaceEventsObserver\n *  ZoneEventsObserver\n *  BeaconEventsObserver.\n * Read the protocols specification in the MOCARegion.h header\n * @param regionObserver region observer\n */\n+ (void)addRegionObserver:(id <RegionEventsObserver>)regionObserver;\n\n/**\n * Removes a region observer.\n * @param regionObserver class to be removed.\n */\n+ (void)removeRegionObserver:(id <RegionEventsObserver>)regionObserver;\n```\n\nThe `MOCAProximityActionsDelegate` has been removed. In order to handle custom actions, register the handler as follows:\n\n`MOCA.customActionHandler = self;` \n\nWhere `self` implements the `MOCACustomActionHandler` protocol.","updates":[],"order":0,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-11-03T17:31:14.302Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Migration guide from 2.x to 3.x


Migration guide from 2.x to 3.x ### MOCA.h API changes Changed methods: - `[MOCA version]`; Has changed to: `MOCA.sdKVersion;` -------- - `+(void) trackViewed:(NSString*) itemId belongingTo:(NSString*)category withReco:(BOOL)recommended;` Has changed to: - `+ (void)trackViewed:(NSString *)itemId belongingTo:(NSString *)category wasRecommended:(BOOL)recommended;` -------- The following accessors are now properties instead of method calls. `appKey` `appSecret` `config` (e.g (Objective-C) Use `MOCA.appKey` instead of [MOCA appKey]) -------- The following methods have been removed: ``` +(CLLocation*) getLastKnownLocation; //UILocalNotification no longer supported +(void)handleLocalNotification:(UILocalNotification *)notification; +(BOOL)isMocaLocalNotification:(UILocalNotification *)notification; +(BOOL)handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification; ``` -------- ### Event and action listener changes The `MOCAProximityEventsDelegate` protocol has been removed. Use the following methods instead. [Location Events Listener](doc:location-events-listener) ``` /** * Adds a new observer for Region Events (RegionGroups, Places, Zones, Beacons) * Compatible protocols * RegionEventsObserver * RegionGroupEventsObserver * PlaceEventsObserver * ZoneEventsObserver * BeaconEventsObserver. * Read the protocols specification in the MOCARegion.h header * @param regionObserver region observer */ + (void)addRegionObserver:(id <RegionEventsObserver>)regionObserver; /** * Removes a region observer. * @param regionObserver class to be removed. */ + (void)removeRegionObserver:(id <RegionEventsObserver>)regionObserver; ``` The `MOCAProximityActionsDelegate` has been removed. In order to handle custom actions, register the handler as follows: `MOCA.customActionHandler = self;` Where `self` implements the `MOCACustomActionHandler` protocol.
Migration guide from 2.x to 3.x ### MOCA.h API changes Changed methods: - `[MOCA version]`; Has changed to: `MOCA.sdKVersion;` -------- - `+(void) trackViewed:(NSString*) itemId belongingTo:(NSString*)category withReco:(BOOL)recommended;` Has changed to: - `+ (void)trackViewed:(NSString *)itemId belongingTo:(NSString *)category wasRecommended:(BOOL)recommended;` -------- The following accessors are now properties instead of method calls. `appKey` `appSecret` `config` (e.g (Objective-C) Use `MOCA.appKey` instead of [MOCA appKey]) -------- The following methods have been removed: ``` +(CLLocation*) getLastKnownLocation; //UILocalNotification no longer supported +(void)handleLocalNotification:(UILocalNotification *)notification; +(BOOL)isMocaLocalNotification:(UILocalNotification *)notification; +(BOOL)handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification; ``` -------- ### Event and action listener changes The `MOCAProximityEventsDelegate` protocol has been removed. Use the following methods instead. [Location Events Listener](doc:location-events-listener) ``` /** * Adds a new observer for Region Events (RegionGroups, Places, Zones, Beacons) * Compatible protocols * RegionEventsObserver * RegionGroupEventsObserver * PlaceEventsObserver * ZoneEventsObserver * BeaconEventsObserver. * Read the protocols specification in the MOCARegion.h header * @param regionObserver region observer */ + (void)addRegionObserver:(id <RegionEventsObserver>)regionObserver; /** * Removes a region observer. * @param regionObserver class to be removed. */ + (void)removeRegionObserver:(id <RegionEventsObserver>)regionObserver; ``` The `MOCAProximityActionsDelegate` has been removed. In order to handle custom actions, register the handler as follows: `MOCA.customActionHandler = self;` Where `self` implements the `MOCACustomActionHandler` protocol.
{"_id":"5f998577fb81e800451c02f9","__v":0,"hidden":false,"order":1,"parentDoc":null,"slug":"moca-ios-sdk-installation","sync_unique":"","type":"basic","updates":["5732f597b26eb71900f89a3b"],"api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]}},"category":"5f998576fb81e800451c02f3","githubsync":"","link_url":"","version":"5f998577fb81e800451c032f","createdAt":"2015-07-14T22:47:22.161Z","excerpt":"This section describes how to add MOCA iOS SDK to your app.","isReference":false,"project":"559a61d2dbcfd20d00710b39","title":"Installation","body":"## MOCA SDK for iOS\n\nMinumum OS supported: iOS 10\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Option A: Cocoapods\"\n}\n[/block]\nCocoaPods is a dependency manager for Objective-C projects. Learn more [here](http://cocoapods.org/).\n\n1. If you haven't already, install CocoaPods by executing the following: \n\n  ```\n$ sudo gem install cocoapods\n  ```\n \n3.  If you encounter any issues installing cocoapods, please refer to their [getting started guide](https://guides.cocoapods.org/using/getting-started.html)\n  \n2. Create a plain text file named Podfile (or use `touch Podfile` from the command line) in the Xcode project directory with the following content:\n\n  ```\ntarget 'YOUR_TARGET_NAME' do\n         pod 'MOCA', '~> 3.3.0'\nend\n  ```\n\nPlease check what is the latest version of the SDK by [here](https://cocoapods.org/pods/MOCA)\n\n\n3. Install MOCA SDK by executing the following in the Xcode project directory:\n\n  ```\n  pod install\n  ```\n  \n4. Open the project workspace (`<yourProject>.xcworkspace`) instead of the project file (`<yourProject>.xcodeproj`) to ensure that the MOCA SDK dependency is properly loaded. \n[block:api-header]\n{\n  \"title\": \"Swift additional steps\"\n}\n[/block]\nIn order to use the MOCA Header symbols in your Swift application, you'll need to create a _Bridging Header_ file. \n\n1 - [Download the file](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/MOCA-Bridging-Header.h) (or create a new one).\n2 - Copy it to your Xcode project. Ensure you select \"copy if needed\" in the copy dialog box.\n3 - Add the Bridging header to your Xcode Project.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Ensure you have selected \\\"All\\\" options instead of \\\"Basic\\\"\",\n  \"body\": \"Otherwise the option could remain hidden.\"\n}\n[/block]\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/7435c7e-Bridging-Header.png\",\n        \"Bridging-Header.png\",\n        1497,\n        473,\n        \"#ececeb\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Option B: Manual installation\"\n}\n[/block]\n1. To install the MOCA SDK, download latest stable version of [MOCA SDK archive](http://files.mocaplatform.com/releases/moca-ios-sdk-latest.zip).\n2. Xcode with the iOS development kit is required to build an iOS app using MOCA SDK. For a better experience, we recommend Xcode 12.\n4. Unzip the archive.\n\nOnce downloaded the SDK, you’ll need to add all necessary frameworks to your project.\n\n5. Open your project in Xcode.\n6. Add the `libMOCALib.a` static library provided in the SDK archive to your app project. The library is a universal FAT library compiled for the following architectures: `armv7/armv7s/arm64/x86_64/i386`. \n7. Make sure to Copy items into destination group's folder is selected.\n8. Press the Finish button.\n9. Ensure that you have added to your project the following dependent frameworks:\n   - `SystemConfiguration.framework`\n   - `CoreTelephony.framework`\n   - `MobileCoreServices.framework`\n   - `CoreLocation.framework`\n   - `UIKit.framework`\n   - `AudioToolbox.framework`\n   - `libsqlite3.0.dynlib`\n   - `PassKit.framework` (optional, only add if you plan to deploy Passbook cards)\n\n   To do this, select your project file in the file explorer, select your target, and select the Build Phases sub-tab. Under Link Binary with Libraries, press the <i>+ button</i>, to select and add all required frameworks.\n\n10. In Xcode, go to the Build Settings of your project. Next go to the “linking” section and add the flag –ObjC in Other Linker Flags.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/aWxkZDdaS1l5cyU1AszE_xcode.png\",\n        \"xcode.png\",\n        \"846\",\n        \"403\",\n        \"#2d5695\",\n        \"\"\n      ],\n      \"caption\": \"Setting -ObjC linker flag.\"\n    }\n  ]\n}\n[/block]\n####Add the header files\n\n1. Copy the Headers folder from the decompressed file to your XCode project.\n    - Ensure you check the \"copy items if needed\" so headers will be inside your project. \n    - Select the needed target(s), so headers paths will be added automatically. (If you have only one target, select it).\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/j0FWxCVFRcxkuG1x2m2R_add-headers.png\",\n        \"add-headers.png\",\n        \"723\",\n        \"436\",\n        \"#3061a0\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Swift\",\n  \"body\": \"When you add Objective-C header files into your Swift project, Xcode will ask you to create a _Bridging Header_ file. This file allows Xcode to _translate_ the Objective-C methods to Swift. This bridging file allows you to use MOCA SDK methods in Swift.\"\n}\n[/block]\n###Xcode does not find the header files!\n\nIf you cannot `#import <MOCA.h>` within your `AppDelegate`, make sure Xcode has added the Header's path correctly to the project's configuration.\n\nGo to `<<Your Project Name>>/<<Your Build Target>>/Build Settings/Search Paths -> Header Search Paths` and add the header's path. You can use the `$(PROJECT_DIR)` build setting to create relative paths:\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/tlY6a3RmmCN6NAV0wMKg_(PROJECT_DIR).png\",\n        \"(PROJECT_DIR).png\",\n        \"802\",\n        \"361\",\n        \"#1a5cad\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]","link_external":false,"next":{"pages":[],"description":""},"user":"55a575ebaaf9cf1900114d73","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Installation

This section describes how to add MOCA iOS SDK to your app.

## MOCA SDK for iOS Minumum OS supported: iOS 10 [block:api-header] { "type": "basic", "title": "Option A: Cocoapods" } [/block] CocoaPods is a dependency manager for Objective-C projects. Learn more [here](http://cocoapods.org/). 1. If you haven't already, install CocoaPods by executing the following: ``` $ sudo gem install cocoapods ``` 3. If you encounter any issues installing cocoapods, please refer to their [getting started guide](https://guides.cocoapods.org/using/getting-started.html) 2. Create a plain text file named Podfile (or use `touch Podfile` from the command line) in the Xcode project directory with the following content: ``` target 'YOUR_TARGET_NAME' do pod 'MOCA', '~> 3.3.0' end ``` Please check what is the latest version of the SDK by [here](https://cocoapods.org/pods/MOCA) 3. Install MOCA SDK by executing the following in the Xcode project directory: ``` pod install ``` 4. Open the project workspace (`<yourProject>.xcworkspace`) instead of the project file (`<yourProject>.xcodeproj`) to ensure that the MOCA SDK dependency is properly loaded. [block:api-header] { "title": "Swift additional steps" } [/block] In order to use the MOCA Header symbols in your Swift application, you'll need to create a _Bridging Header_ file. 1 - [Download the file](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/MOCA-Bridging-Header.h) (or create a new one). 2 - Copy it to your Xcode project. Ensure you select "copy if needed" in the copy dialog box. 3 - Add the Bridging header to your Xcode Project. [block:callout] { "type": "info", "title": "Ensure you have selected \"All\" options instead of \"Basic\"", "body": "Otherwise the option could remain hidden." } [/block] [block:image] { "images": [ { "image": [ "https://files.readme.io/7435c7e-Bridging-Header.png", "Bridging-Header.png", 1497, 473, "#ececeb" ] } ] } [/block] [block:api-header] { "type": "basic", "title": "Option B: Manual installation" } [/block] 1. To install the MOCA SDK, download latest stable version of [MOCA SDK archive](http://files.mocaplatform.com/releases/moca-ios-sdk-latest.zip). 2. Xcode with the iOS development kit is required to build an iOS app using MOCA SDK. For a better experience, we recommend Xcode 12. 4. Unzip the archive. Once downloaded the SDK, you’ll need to add all necessary frameworks to your project. 5. Open your project in Xcode. 6. Add the `libMOCALib.a` static library provided in the SDK archive to your app project. The library is a universal FAT library compiled for the following architectures: `armv7/armv7s/arm64/x86_64/i386`. 7. Make sure to Copy items into destination group's folder is selected. 8. Press the Finish button. 9. Ensure that you have added to your project the following dependent frameworks: - `SystemConfiguration.framework` - `CoreTelephony.framework` - `MobileCoreServices.framework` - `CoreLocation.framework` - `UIKit.framework` - `AudioToolbox.framework` - `libsqlite3.0.dynlib` - `PassKit.framework` (optional, only add if you plan to deploy Passbook cards) To do this, select your project file in the file explorer, select your target, and select the Build Phases sub-tab. Under Link Binary with Libraries, press the <i>+ button</i>, to select and add all required frameworks. 10. In Xcode, go to the Build Settings of your project. Next go to the “linking” section and add the flag –ObjC in Other Linker Flags. [block:image] { "images": [ { "image": [ "https://files.readme.io/aWxkZDdaS1l5cyU1AszE_xcode.png", "xcode.png", "846", "403", "#2d5695", "" ], "caption": "Setting -ObjC linker flag." } ] } [/block] ####Add the header files 1. Copy the Headers folder from the decompressed file to your XCode project. - Ensure you check the "copy items if needed" so headers will be inside your project. - Select the needed target(s), so headers paths will be added automatically. (If you have only one target, select it). [block:image] { "images": [ { "image": [ "https://files.readme.io/j0FWxCVFRcxkuG1x2m2R_add-headers.png", "add-headers.png", "723", "436", "#3061a0", "" ] } ] } [/block] [block:callout] { "type": "warning", "title": "Swift", "body": "When you add Objective-C header files into your Swift project, Xcode will ask you to create a _Bridging Header_ file. This file allows Xcode to _translate_ the Objective-C methods to Swift. This bridging file allows you to use MOCA SDK methods in Swift." } [/block] ###Xcode does not find the header files! If you cannot `#import <MOCA.h>` within your `AppDelegate`, make sure Xcode has added the Header's path correctly to the project's configuration. Go to `<<Your Project Name>>/<<Your Build Target>>/Build Settings/Search Paths -> Header Search Paths` and add the header's path. You can use the `$(PROJECT_DIR)` build setting to create relative paths: [block:image] { "images": [ { "image": [ "https://files.readme.io/tlY6a3RmmCN6NAV0wMKg_(PROJECT_DIR).png", "(PROJECT_DIR).png", "802", "361", "#1a5cad", "" ] } ] } [/block]
## MOCA SDK for iOS Minumum OS supported: iOS 10 [block:api-header] { "type": "basic", "title": "Option A: Cocoapods" } [/block] CocoaPods is a dependency manager for Objective-C projects. Learn more [here](http://cocoapods.org/). 1. If you haven't already, install CocoaPods by executing the following: ``` $ sudo gem install cocoapods ``` 3. If you encounter any issues installing cocoapods, please refer to their [getting started guide](https://guides.cocoapods.org/using/getting-started.html) 2. Create a plain text file named Podfile (or use `touch Podfile` from the command line) in the Xcode project directory with the following content: ``` target 'YOUR_TARGET_NAME' do pod 'MOCA', '~> 3.3.0' end ``` Please check what is the latest version of the SDK by [here](https://cocoapods.org/pods/MOCA) 3. Install MOCA SDK by executing the following in the Xcode project directory: ``` pod install ``` 4. Open the project workspace (`<yourProject>.xcworkspace`) instead of the project file (`<yourProject>.xcodeproj`) to ensure that the MOCA SDK dependency is properly loaded. [block:api-header] { "title": "Swift additional steps" } [/block] In order to use the MOCA Header symbols in your Swift application, you'll need to create a _Bridging Header_ file. 1 - [Download the file](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/MOCA-Bridging-Header.h) (or create a new one). 2 - Copy it to your Xcode project. Ensure you select "copy if needed" in the copy dialog box. 3 - Add the Bridging header to your Xcode Project. [block:callout] { "type": "info", "title": "Ensure you have selected \"All\" options instead of \"Basic\"", "body": "Otherwise the option could remain hidden." } [/block] [block:image] { "images": [ { "image": [ "https://files.readme.io/7435c7e-Bridging-Header.png", "Bridging-Header.png", 1497, 473, "#ececeb" ] } ] } [/block] [block:api-header] { "type": "basic", "title": "Option B: Manual installation" } [/block] 1. To install the MOCA SDK, download latest stable version of [MOCA SDK archive](http://files.mocaplatform.com/releases/moca-ios-sdk-latest.zip). 2. Xcode with the iOS development kit is required to build an iOS app using MOCA SDK. For a better experience, we recommend Xcode 12. 4. Unzip the archive. Once downloaded the SDK, you’ll need to add all necessary frameworks to your project. 5. Open your project in Xcode. 6. Add the `libMOCALib.a` static library provided in the SDK archive to your app project. The library is a universal FAT library compiled for the following architectures: `armv7/armv7s/arm64/x86_64/i386`. 7. Make sure to Copy items into destination group's folder is selected. 8. Press the Finish button. 9. Ensure that you have added to your project the following dependent frameworks: - `SystemConfiguration.framework` - `CoreTelephony.framework` - `MobileCoreServices.framework` - `CoreLocation.framework` - `UIKit.framework` - `AudioToolbox.framework` - `libsqlite3.0.dynlib` - `PassKit.framework` (optional, only add if you plan to deploy Passbook cards) To do this, select your project file in the file explorer, select your target, and select the Build Phases sub-tab. Under Link Binary with Libraries, press the <i>+ button</i>, to select and add all required frameworks. 10. In Xcode, go to the Build Settings of your project. Next go to the “linking” section and add the flag –ObjC in Other Linker Flags. [block:image] { "images": [ { "image": [ "https://files.readme.io/aWxkZDdaS1l5cyU1AszE_xcode.png", "xcode.png", "846", "403", "#2d5695", "" ], "caption": "Setting -ObjC linker flag." } ] } [/block] ####Add the header files 1. Copy the Headers folder from the decompressed file to your XCode project. - Ensure you check the "copy items if needed" so headers will be inside your project. - Select the needed target(s), so headers paths will be added automatically. (If you have only one target, select it). [block:image] { "images": [ { "image": [ "https://files.readme.io/j0FWxCVFRcxkuG1x2m2R_add-headers.png", "add-headers.png", "723", "436", "#3061a0", "" ] } ] } [/block] [block:callout] { "type": "warning", "title": "Swift", "body": "When you add Objective-C header files into your Swift project, Xcode will ask you to create a _Bridging Header_ file. This file allows Xcode to _translate_ the Objective-C methods to Swift. This bridging file allows you to use MOCA SDK methods in Swift." } [/block] ###Xcode does not find the header files! If you cannot `#import <MOCA.h>` within your `AppDelegate`, make sure Xcode has added the Header's path correctly to the project's configuration. Go to `<<Your Project Name>>/<<Your Build Target>>/Build Settings/Search Paths -> Header Search Paths` and add the header's path. You can use the `$(PROJECT_DIR)` build setting to create relative paths: [block:image] { "images": [ { "image": [ "https://files.readme.io/tlY6a3RmmCN6NAV0wMKg_(PROJECT_DIR).png", "(PROJECT_DIR).png", "802", "361", "#1a5cad", "" ] } ] } [/block]
{"_id":"5f998577fb81e800451c02fa","api":{"auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":""},"createdAt":"2015-07-15T00:58:32.707Z","parentDoc":null,"user":"55a575ebaaf9cf1900114d73","__v":0,"link_url":"","project":"559a61d2dbcfd20d00710b39","version":"5f998577fb81e800451c032f","body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Location Services\"\n}\n[/block]\nDeclare the following permissions in case you want to use the Geofencing and Bluetooth Beacon detection features of the platform in your `Info.plist` file. Customize the text with an appropriate wording for your context and application.\n\n| **Key**                                      | **Type** |                                                                                                                                 |\n|----------------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------------------|\n| NSLocationAlwaysUsageDescription             | String   | This app will use your location information to identify ,nearby places and to notify you about available proximity experiences. |\n| NSLocationAlwaysAndWhenInUseUsageDescription | String   | Always location permission is needed in order to detect bluetooth beacons and geofences                                         |\n| NSLocationWhenInUseUsageDescription          | String   | When app is in use location permission will be used to notify you about relevant content around your location                   |\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"body\": \"If this key is not present in your `info.plist`, iOS Location Services **won't start**, preventing the App from detecting Bluetooth Beacons, Geofences and from receiving Location updates.\",\n  \"title\": \"Important\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"This message will be prompted to the user when asked for location services permission. Please bear in mind that if this key is not present in your info.plist, location services** won’t work at all.**\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Requesting permissions on runtime\"\n}\n[/block]\nMOCA SDK can conveniently request the location and notification permissions for you, out of the box. However, the SDK will ask for the permissions *as soon as it is initialized*. This means that the user could potentially see too many permission request prompts *without understanding the purpose of them and without context*. This is the default behavior.\n\nWe strongly recommend that your application request these permissions. \n\n### Enable or disable SDK auto permission request\n\nIn the `MOCAConfig.plist`\n\nKey name: `LOCATION_PERMISSION_REQUEST_MODE`\nPossible values: \n- `auto`: Default value. SDK will request the \"Always\" permission as soon as possible. \n- `WhenInUse`: SDK will request the permission \"When in Use\". This permission limits the ability to detect beacons and geofence in the background.\n- `Disabled`: MOCA SDK won't request location permissions.\n\nKey name: `REQUEST_NOTIFICATIONS_PERMISSION`\nPossible values: \n- `Yes`: Default value. SDK will request the permission on SDK initialization. \n- `No`: SDK will not request the permission.\n\n\nNOTE: If you choose the `Disabled` option. Call the following methods as soon as the user grants you the permission:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setGeoTrackingEnabled(true);\\nMOCA.setProximityEnabled(true);\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA setGeoTrackingEnabled:YES];\\n[MOCA setProximityEnabled:YES];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"App Transport Security\"\n}\n[/block]\n###App Transport Security\n\niOS 9 blocks all non-HTTPS requests, as you probably may want to show content hosted in non-HTTPS servers, please add the following keys to your `info.plist`:\nBear in mind you can use the key description (see image) instead of the key (NS...).\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/W02ZcgadS36yvqYZi01v_ios%209%20app%20transport.png\",\n        \"ios 9 app transport.png\",\n        \"438\",\n        \"75\",\n        \"#114b9a\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\nUsing key's descriptions.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/2Ch7Pe6vRneAKw4igre9_infoplist2.png\",\n        \"infoplist2.png\",\n        \"500\",\n        \"49\",\n        \"#764f40\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Universal Links\"\n}\n[/block]\nIn order to use Universal Links within MOCA Campaigns. (e.g. Once a user clicks on a notification, it opens a specific screen of your app using a universal link), you need to declare the domains your application support in the SDK `MOCAConfig.plist` as follows:\n\nKey: `MOCA_UNIVERSAL_KEY_DOMAINS`\nType: `Array`\nValue: [Array of Domains]\n\nExample:\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/61d142e-Captura_de_pantalla_2020-10-28_a_las_16.33.46.png\",\n        \"Captura de pantalla 2020-10-28 a las 16.33.46.png\",\n        1272,\n        80,\n        \"#333\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Custom Schemes\"\n}\n[/block]\nIf your app uses custom schemes, MOCA SDK supports it out of the box.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"App Capabilities\"\n}\n[/block]\nMOCA SDK requires the app to enable selected *Capabilities*. Open XCode with your app project, go to Target, and select *Capabilities* configuration page. \n\nFirst, within *Background Modes* section, ensure the following entitlements are enabled:\n   - Background Fetch\n   - Remote Notifications\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/mU6VBI2JSBW2sgCVaBak_background-capabilities.png\",\n        \"background-capabilities.png\",\n        \"817\",\n        \"282\",\n        \"\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"body\": \"**Do not** select *Location updates* (unless you need it for another App feature). MOCA SDK **does not require this mode**. If you enable it and do not use it for any purpose, **your App will be rejected** by Apple.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"App Keys\"\n}\n[/block]\nTo link you app to your MOCA account, you must register the app in the MOCA Console and add corresponding **AppKey** and **AppSecret**. \n\n* Goto [https://console.mocaplatform.com](https://console.mocaplatform.com) and sign in to your MOCA account.\n* Select Apps item at left sidebar, and then click <i>+ New App</i> in the content panel or select your existing App.\n* Navigate to <i>Settings</i> item. Select <i>API keys</i> tab.\n* Get `App Key` and `App Secret`.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/FFeK1tqTwCqIjweq7aP9_moca-keys.png\",\n        \"moca-keys.png\",\n        \"704\",\n        \"458\",\n        \"#573033\",\n        \"\"\n      ],\n      \"caption\": \"App keys in MOCA Console\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Environment\",\n  \"body\": \"We highly recommend creating at least two apps: A \\\"Development\\\" version, and a \\\"Production\\\" version. Select the appropriate environment in the settings (Prod or Dev). \\n*The MOCA environment determines whether if the remote notifications are sent via APNS dev or prod servers.*\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"SDK Configuration File\"\n}\n[/block]\nNow, you’ll need to prepare SDK configuration file:\n\n* Go back to your Xcode project.\n* `CocoaPods` only: You will find the MOCAConfig.plist in the following path: `Pods/MOCA/Resources` there is no need to add it manually\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/6Q8t5NjZSICU3QYn0TeF_MOCAConfig-cocoapods.png\",\n        \"MOCAConfig-cocoapods.png\",\n        \"261\",\n        \"168\",\n        \"#97571e\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n* Add <i>New file / Property List</i> resource to your project. Save it as *MOCAConfig.plist* file. (optional,  [download sample MOCAConfig.plist file](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/MOCAConfig.plist))\n* Add configuration settings as shown below.\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Key\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Default Value\",\n    \"h-3\": \"Description\",\n    \"h-4\": \"\",\n    \"0-0\": \"APP_KEY\",\n    \"0-1\": \"String\",\n    \"0-3\": \"App key from MOCA Console\",\n    \"1-0\": \"APP_SECRET\",\n    \"1-1\": \"String\",\n    \"1-3\": \"App secret from MOCA Console\",\n    \"2-0\": \"LOG_LEVEL\",\n    \"2-1\": \"String\",\n    \"2-3\": \"MOCA SDK logging level:\\n* trace\\n* debug\\n* info\\n* warn\\n* error\",\n    \"2-2\": \"\\\"info\\\"\",\n    \"3-0\": \"CACHE_DISK_SIZE_IN_MB\",\n    \"3-1\": \"Integer\",\n    \"3-3\": \"Maximum local disk space available for SDK cache.\",\n    \"3-2\": \"100\",\n    \"4-0\": \"AUTOMATIC_PUSH_SETUP_ENABLED\",\n    \"4-3\": \"If enabled, the SDK will automatically subscribe the app to APNS (Apple push notification service) and obtain push token.\",\n    \"4-1\": \"BOOL\",\n    \"4-2\": \"YES\",\n    \"5-0\": \"PROXIMITY_SERVICE_ENABLED\",\n    \"5-1\": \"BOOL\",\n    \"5-2\": \"YES\",\n    \"5-3\": \"Enables or disables Bluetooth Beacon monitoring and ranging & geofence detection using *iOS Location Services*\",\n    \"6-0\": \"GEOLOCATION_SERVICE_ENABLED\",\n    \"6-1\": \"BOOL\",\n    \"6-2\": \"YES\",\n    \"6-3\": \"Enables/disables tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\\n\\nWhen enabled (YES), user location will be tracked when the app is in foreground. Additionally, background tracking is controlled by BACKGROUND_LOCATION_ENABLED flag. This is the default.\\n\\nWhen disabled (NO), user location will not be tracked at all (neither in foreground nor on background). However, Bluetooth beacons and geofences will still be detected if this flag is set to NO.\"\n  },\n  \"cols\": 4,\n  \"rows\": 7\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"MOCA performs location tracking using low battery usage modes to save battery life. For example, when the app is in background GPS-quality tracking is never used.\",\n  \"sidebar\": true\n}\n[/block]\n* Be sure to replace `APP_KEY` and `APP_SECRET` values with the real values for your app which you found in the MOCA console.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/ncAD6MeQJy2CCfiVWjtm_moca-config-ios.png\",\n        \"moca-config-ios.png\",\n        \"949\",\n        \"369\",\n        \"#884c39\",\n        \"\"\n      ],\n      \"caption\": \"Sample MOCAConfig.plist file.\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Other `MOCAConfig.plist` settings\"\n}\n[/block]\nKey: `OVERLAY_DELAY_ON_STARTUP_SECONDS`\nType: `NUMBER`\nDefault value: `3`\n\nSome MOCA Campaigns consist of two parts: \n- A notification\n- An overlay that is shown on top of the application once the user taps on the notification.\n\nIf the application is not running when the user taps on the notification, the SDK will wait `OVERLAY_DELAY_ON_STARTUP_SECONDS` seconds before attempting to show the content as an overlay. \n\nIf your application tends to take more time to start up. Change this setting accordingly.","githubsync":"","hidden":false,"link_external":false,"next":{"pages":[],"description":""},"sync_unique":"","title":"Configuration","type":"basic","category":"5f998576fb81e800451c02f3","excerpt":"This section describes how to configure MOCA iOS SDK in your app.","isReference":false,"order":2,"slug":"moca-ios-sdk-configuration","updates":[],"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Configuration

This section describes how to configure MOCA iOS SDK in your app.

[block:api-header] { "type": "basic", "title": "Location Services" } [/block] Declare the following permissions in case you want to use the Geofencing and Bluetooth Beacon detection features of the platform in your `Info.plist` file. Customize the text with an appropriate wording for your context and application. | **Key** | **Type** | | |----------------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------------------| | NSLocationAlwaysUsageDescription | String | This app will use your location information to identify ,nearby places and to notify you about available proximity experiences. | | NSLocationAlwaysAndWhenInUseUsageDescription | String | Always location permission is needed in order to detect bluetooth beacons and geofences | | NSLocationWhenInUseUsageDescription | String | When app is in use location permission will be used to notify you about relevant content around your location | [block:callout] { "type": "danger", "body": "If this key is not present in your `info.plist`, iOS Location Services **won't start**, preventing the App from detecting Bluetooth Beacons, Geofences and from receiving Location updates.", "title": "Important" } [/block] [block:callout] { "type": "warning", "body": "This message will be prompted to the user when asked for location services permission. Please bear in mind that if this key is not present in your info.plist, location services** won’t work at all.**", "sidebar": true } [/block] [block:api-header] { "title": "Requesting permissions on runtime" } [/block] MOCA SDK can conveniently request the location and notification permissions for you, out of the box. However, the SDK will ask for the permissions *as soon as it is initialized*. This means that the user could potentially see too many permission request prompts *without understanding the purpose of them and without context*. This is the default behavior. We strongly recommend that your application request these permissions. ### Enable or disable SDK auto permission request In the `MOCAConfig.plist` Key name: `LOCATION_PERMISSION_REQUEST_MODE` Possible values: - `auto`: Default value. SDK will request the "Always" permission as soon as possible. - `WhenInUse`: SDK will request the permission "When in Use". This permission limits the ability to detect beacons and geofence in the background. - `Disabled`: MOCA SDK won't request location permissions. Key name: `REQUEST_NOTIFICATIONS_PERMISSION` Possible values: - `Yes`: Default value. SDK will request the permission on SDK initialization. - `No`: SDK will not request the permission. NOTE: If you choose the `Disabled` option. Call the following methods as soon as the user grants you the permission: [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true);\nMOCA.setProximityEnabled(true);", "language": "swift" }, { "code": "[MOCA setGeoTrackingEnabled:YES];\n[MOCA setProximityEnabled:YES];", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "App Transport Security" } [/block] ###App Transport Security iOS 9 blocks all non-HTTPS requests, as you probably may want to show content hosted in non-HTTPS servers, please add the following keys to your `info.plist`: Bear in mind you can use the key description (see image) instead of the key (NS...). [block:image] { "images": [ { "image": [ "https://files.readme.io/W02ZcgadS36yvqYZi01v_ios%209%20app%20transport.png", "ios 9 app transport.png", "438", "75", "#114b9a", "" ] } ] } [/block] Using key's descriptions. [block:image] { "images": [ { "image": [ "https://files.readme.io/2Ch7Pe6vRneAKw4igre9_infoplist2.png", "infoplist2.png", "500", "49", "#764f40", "" ] } ] } [/block] [block:api-header] { "title": "Universal Links" } [/block] In order to use Universal Links within MOCA Campaigns. (e.g. Once a user clicks on a notification, it opens a specific screen of your app using a universal link), you need to declare the domains your application support in the SDK `MOCAConfig.plist` as follows: Key: `MOCA_UNIVERSAL_KEY_DOMAINS` Type: `Array` Value: [Array of Domains] Example: [block:image] { "images": [ { "image": [ "https://files.readme.io/61d142e-Captura_de_pantalla_2020-10-28_a_las_16.33.46.png", "Captura de pantalla 2020-10-28 a las 16.33.46.png", 1272, 80, "#333" ] } ] } [/block] [block:api-header] { "title": "Custom Schemes" } [/block] If your app uses custom schemes, MOCA SDK supports it out of the box. [block:api-header] { "type": "basic", "title": "App Capabilities" } [/block] MOCA SDK requires the app to enable selected *Capabilities*. Open XCode with your app project, go to Target, and select *Capabilities* configuration page. First, within *Background Modes* section, ensure the following entitlements are enabled: - Background Fetch - Remote Notifications [block:image] { "images": [ { "image": [ "https://files.readme.io/mU6VBI2JSBW2sgCVaBak_background-capabilities.png", "background-capabilities.png", "817", "282", "", "" ] } ] } [/block] [block:callout] { "type": "danger", "body": "**Do not** select *Location updates* (unless you need it for another App feature). MOCA SDK **does not require this mode**. If you enable it and do not use it for any purpose, **your App will be rejected** by Apple." } [/block] [block:api-header] { "type": "basic", "title": "App Keys" } [/block] To link you app to your MOCA account, you must register the app in the MOCA Console and add corresponding **AppKey** and **AppSecret**. * Goto [https://console.mocaplatform.com](https://console.mocaplatform.com) and sign in to your MOCA account. * Select Apps item at left sidebar, and then click <i>+ New App</i> in the content panel or select your existing App. * Navigate to <i>Settings</i> item. Select <i>API keys</i> tab. * Get `App Key` and `App Secret`. [block:image] { "images": [ { "image": [ "https://files.readme.io/FFeK1tqTwCqIjweq7aP9_moca-keys.png", "moca-keys.png", "704", "458", "#573033", "" ], "caption": "App keys in MOCA Console" } ] } [/block] [block:callout] { "type": "warning", "title": "Environment", "body": "We highly recommend creating at least two apps: A \"Development\" version, and a \"Production\" version. Select the appropriate environment in the settings (Prod or Dev). \n*The MOCA environment determines whether if the remote notifications are sent via APNS dev or prod servers.*" } [/block] [block:api-header] { "type": "basic", "title": "SDK Configuration File" } [/block] Now, you’ll need to prepare SDK configuration file: * Go back to your Xcode project. * `CocoaPods` only: You will find the MOCAConfig.plist in the following path: `Pods/MOCA/Resources` there is no need to add it manually [block:image] { "images": [ { "image": [ "https://files.readme.io/6Q8t5NjZSICU3QYn0TeF_MOCAConfig-cocoapods.png", "MOCAConfig-cocoapods.png", "261", "168", "#97571e", "" ] } ] } [/block] * Add <i>New file / Property List</i> resource to your project. Save it as *MOCAConfig.plist* file. (optional, [download sample MOCAConfig.plist file](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/MOCAConfig.plist)) * Add configuration settings as shown below. [block:parameters] { "data": { "h-0": "Key", "h-1": "Type", "h-2": "Default Value", "h-3": "Description", "h-4": "", "0-0": "APP_KEY", "0-1": "String", "0-3": "App key from MOCA Console", "1-0": "APP_SECRET", "1-1": "String", "1-3": "App secret from MOCA Console", "2-0": "LOG_LEVEL", "2-1": "String", "2-3": "MOCA SDK logging level:\n* trace\n* debug\n* info\n* warn\n* error", "2-2": "\"info\"", "3-0": "CACHE_DISK_SIZE_IN_MB", "3-1": "Integer", "3-3": "Maximum local disk space available for SDK cache.", "3-2": "100", "4-0": "AUTOMATIC_PUSH_SETUP_ENABLED", "4-3": "If enabled, the SDK will automatically subscribe the app to APNS (Apple push notification service) and obtain push token.", "4-1": "BOOL", "4-2": "YES", "5-0": "PROXIMITY_SERVICE_ENABLED", "5-1": "BOOL", "5-2": "YES", "5-3": "Enables or disables Bluetooth Beacon monitoring and ranging & geofence detection using *iOS Location Services*", "6-0": "GEOLOCATION_SERVICE_ENABLED", "6-1": "BOOL", "6-2": "YES", "6-3": "Enables/disables tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\n\nWhen enabled (YES), user location will be tracked when the app is in foreground. Additionally, background tracking is controlled by BACKGROUND_LOCATION_ENABLED flag. This is the default.\n\nWhen disabled (NO), user location will not be tracked at all (neither in foreground nor on background). However, Bluetooth beacons and geofences will still be detected if this flag is set to NO." }, "cols": 4, "rows": 7 } [/block] [block:callout] { "type": "info", "body": "MOCA performs location tracking using low battery usage modes to save battery life. For example, when the app is in background GPS-quality tracking is never used.", "sidebar": true } [/block] * Be sure to replace `APP_KEY` and `APP_SECRET` values with the real values for your app which you found in the MOCA console. [block:image] { "images": [ { "image": [ "https://files.readme.io/ncAD6MeQJy2CCfiVWjtm_moca-config-ios.png", "moca-config-ios.png", "949", "369", "#884c39", "" ], "caption": "Sample MOCAConfig.plist file." } ] } [/block] [block:api-header] { "title": "Other `MOCAConfig.plist` settings" } [/block] Key: `OVERLAY_DELAY_ON_STARTUP_SECONDS` Type: `NUMBER` Default value: `3` Some MOCA Campaigns consist of two parts: - A notification - An overlay that is shown on top of the application once the user taps on the notification. If the application is not running when the user taps on the notification, the SDK will wait `OVERLAY_DELAY_ON_STARTUP_SECONDS` seconds before attempting to show the content as an overlay. If your application tends to take more time to start up. Change this setting accordingly.
[block:api-header] { "type": "basic", "title": "Location Services" } [/block] Declare the following permissions in case you want to use the Geofencing and Bluetooth Beacon detection features of the platform in your `Info.plist` file. Customize the text with an appropriate wording for your context and application. | **Key** | **Type** | | |----------------------------------------------|----------|---------------------------------------------------------------------------------------------------------------------------------| | NSLocationAlwaysUsageDescription | String | This app will use your location information to identify ,nearby places and to notify you about available proximity experiences. | | NSLocationAlwaysAndWhenInUseUsageDescription | String | Always location permission is needed in order to detect bluetooth beacons and geofences | | NSLocationWhenInUseUsageDescription | String | When app is in use location permission will be used to notify you about relevant content around your location | [block:callout] { "type": "danger", "body": "If this key is not present in your `info.plist`, iOS Location Services **won't start**, preventing the App from detecting Bluetooth Beacons, Geofences and from receiving Location updates.", "title": "Important" } [/block] [block:callout] { "type": "warning", "body": "This message will be prompted to the user when asked for location services permission. Please bear in mind that if this key is not present in your info.plist, location services** won’t work at all.**", "sidebar": true } [/block] [block:api-header] { "title": "Requesting permissions on runtime" } [/block] MOCA SDK can conveniently request the location and notification permissions for you, out of the box. However, the SDK will ask for the permissions *as soon as it is initialized*. This means that the user could potentially see too many permission request prompts *without understanding the purpose of them and without context*. This is the default behavior. We strongly recommend that your application request these permissions. ### Enable or disable SDK auto permission request In the `MOCAConfig.plist` Key name: `LOCATION_PERMISSION_REQUEST_MODE` Possible values: - `auto`: Default value. SDK will request the "Always" permission as soon as possible. - `WhenInUse`: SDK will request the permission "When in Use". This permission limits the ability to detect beacons and geofence in the background. - `Disabled`: MOCA SDK won't request location permissions. Key name: `REQUEST_NOTIFICATIONS_PERMISSION` Possible values: - `Yes`: Default value. SDK will request the permission on SDK initialization. - `No`: SDK will not request the permission. NOTE: If you choose the `Disabled` option. Call the following methods as soon as the user grants you the permission: [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true);\nMOCA.setProximityEnabled(true);", "language": "swift" }, { "code": "[MOCA setGeoTrackingEnabled:YES];\n[MOCA setProximityEnabled:YES];", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "App Transport Security" } [/block] ###App Transport Security iOS 9 blocks all non-HTTPS requests, as you probably may want to show content hosted in non-HTTPS servers, please add the following keys to your `info.plist`: Bear in mind you can use the key description (see image) instead of the key (NS...). [block:image] { "images": [ { "image": [ "https://files.readme.io/W02ZcgadS36yvqYZi01v_ios%209%20app%20transport.png", "ios 9 app transport.png", "438", "75", "#114b9a", "" ] } ] } [/block] Using key's descriptions. [block:image] { "images": [ { "image": [ "https://files.readme.io/2Ch7Pe6vRneAKw4igre9_infoplist2.png", "infoplist2.png", "500", "49", "#764f40", "" ] } ] } [/block] [block:api-header] { "title": "Universal Links" } [/block] In order to use Universal Links within MOCA Campaigns. (e.g. Once a user clicks on a notification, it opens a specific screen of your app using a universal link), you need to declare the domains your application support in the SDK `MOCAConfig.plist` as follows: Key: `MOCA_UNIVERSAL_KEY_DOMAINS` Type: `Array` Value: [Array of Domains] Example: [block:image] { "images": [ { "image": [ "https://files.readme.io/61d142e-Captura_de_pantalla_2020-10-28_a_las_16.33.46.png", "Captura de pantalla 2020-10-28 a las 16.33.46.png", 1272, 80, "#333" ] } ] } [/block] [block:api-header] { "title": "Custom Schemes" } [/block] If your app uses custom schemes, MOCA SDK supports it out of the box. [block:api-header] { "type": "basic", "title": "App Capabilities" } [/block] MOCA SDK requires the app to enable selected *Capabilities*. Open XCode with your app project, go to Target, and select *Capabilities* configuration page. First, within *Background Modes* section, ensure the following entitlements are enabled: - Background Fetch - Remote Notifications [block:image] { "images": [ { "image": [ "https://files.readme.io/mU6VBI2JSBW2sgCVaBak_background-capabilities.png", "background-capabilities.png", "817", "282", "", "" ] } ] } [/block] [block:callout] { "type": "danger", "body": "**Do not** select *Location updates* (unless you need it for another App feature). MOCA SDK **does not require this mode**. If you enable it and do not use it for any purpose, **your App will be rejected** by Apple." } [/block] [block:api-header] { "type": "basic", "title": "App Keys" } [/block] To link you app to your MOCA account, you must register the app in the MOCA Console and add corresponding **AppKey** and **AppSecret**. * Goto [https://console.mocaplatform.com](https://console.mocaplatform.com) and sign in to your MOCA account. * Select Apps item at left sidebar, and then click <i>+ New App</i> in the content panel or select your existing App. * Navigate to <i>Settings</i> item. Select <i>API keys</i> tab. * Get `App Key` and `App Secret`. [block:image] { "images": [ { "image": [ "https://files.readme.io/FFeK1tqTwCqIjweq7aP9_moca-keys.png", "moca-keys.png", "704", "458", "#573033", "" ], "caption": "App keys in MOCA Console" } ] } [/block] [block:callout] { "type": "warning", "title": "Environment", "body": "We highly recommend creating at least two apps: A \"Development\" version, and a \"Production\" version. Select the appropriate environment in the settings (Prod or Dev). \n*The MOCA environment determines whether if the remote notifications are sent via APNS dev or prod servers.*" } [/block] [block:api-header] { "type": "basic", "title": "SDK Configuration File" } [/block] Now, you’ll need to prepare SDK configuration file: * Go back to your Xcode project. * `CocoaPods` only: You will find the MOCAConfig.plist in the following path: `Pods/MOCA/Resources` there is no need to add it manually [block:image] { "images": [ { "image": [ "https://files.readme.io/6Q8t5NjZSICU3QYn0TeF_MOCAConfig-cocoapods.png", "MOCAConfig-cocoapods.png", "261", "168", "#97571e", "" ] } ] } [/block] * Add <i>New file / Property List</i> resource to your project. Save it as *MOCAConfig.plist* file. (optional, [download sample MOCAConfig.plist file](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/MOCAConfig.plist)) * Add configuration settings as shown below. [block:parameters] { "data": { "h-0": "Key", "h-1": "Type", "h-2": "Default Value", "h-3": "Description", "h-4": "", "0-0": "APP_KEY", "0-1": "String", "0-3": "App key from MOCA Console", "1-0": "APP_SECRET", "1-1": "String", "1-3": "App secret from MOCA Console", "2-0": "LOG_LEVEL", "2-1": "String", "2-3": "MOCA SDK logging level:\n* trace\n* debug\n* info\n* warn\n* error", "2-2": "\"info\"", "3-0": "CACHE_DISK_SIZE_IN_MB", "3-1": "Integer", "3-3": "Maximum local disk space available for SDK cache.", "3-2": "100", "4-0": "AUTOMATIC_PUSH_SETUP_ENABLED", "4-3": "If enabled, the SDK will automatically subscribe the app to APNS (Apple push notification service) and obtain push token.", "4-1": "BOOL", "4-2": "YES", "5-0": "PROXIMITY_SERVICE_ENABLED", "5-1": "BOOL", "5-2": "YES", "5-3": "Enables or disables Bluetooth Beacon monitoring and ranging & geofence detection using *iOS Location Services*", "6-0": "GEOLOCATION_SERVICE_ENABLED", "6-1": "BOOL", "6-2": "YES", "6-3": "Enables/disables tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\n\nWhen enabled (YES), user location will be tracked when the app is in foreground. Additionally, background tracking is controlled by BACKGROUND_LOCATION_ENABLED flag. This is the default.\n\nWhen disabled (NO), user location will not be tracked at all (neither in foreground nor on background). However, Bluetooth beacons and geofences will still be detected if this flag is set to NO." }, "cols": 4, "rows": 7 } [/block] [block:callout] { "type": "info", "body": "MOCA performs location tracking using low battery usage modes to save battery life. For example, when the app is in background GPS-quality tracking is never used.", "sidebar": true } [/block] * Be sure to replace `APP_KEY` and `APP_SECRET` values with the real values for your app which you found in the MOCA console. [block:image] { "images": [ { "image": [ "https://files.readme.io/ncAD6MeQJy2CCfiVWjtm_moca-config-ios.png", "moca-config-ios.png", "949", "369", "#884c39", "" ], "caption": "Sample MOCAConfig.plist file." } ] } [/block] [block:api-header] { "title": "Other `MOCAConfig.plist` settings" } [/block] Key: `OVERLAY_DELAY_ON_STARTUP_SECONDS` Type: `NUMBER` Default value: `3` Some MOCA Campaigns consist of two parts: - A notification - An overlay that is shown on top of the application once the user taps on the notification. If the application is not running when the user taps on the notification, the SDK will wait `OVERLAY_DELAY_ON_STARTUP_SECONDS` seconds before attempting to show the content as an overlay. If your application tends to take more time to start up. Change this setting accordingly.
{"_id":"5f998577fb81e800451c02fb","title":"Integration","order":3,"slug":"moca-ios-sdk-integration","parentDoc":null,"version":"5f998577fb81e800451c032f","__v":0,"excerpt":"This section describes how to integrate MOCA iOS SDK with your app code.","category":"5f998576fb81e800451c02f3","githubsync":"","isReference":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","type":"basic","body":"[block:api-header]\n{\n  \"title\": \"\\\"Show me the code\\\" Integration\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\\n        let mocaStarted = MOCA.initializeSDK()\\n        if !mocaStarted {\\n            print(\\\"Cannot initialize MOCA SDK\\\")\\n        }\\n        let center = UNUserNotificationCenter.current()\\n        center.delegate = self\\n        return true\\n    }\\n    \\n    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\\n        if(MOCA.initialized() && MOCA.isMocaNotification(notification)) {\\n            MOCA.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)\\n        }\\n\\n    }\\n    \\n    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\\n        if(MOCA.initialized() && MOCA.isMocaNotification(response)) {\\n            MOCA.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)\\n        }\\n    }\\n    \\n    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\\n     if MOCA.initialized() {\\n         MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\\n     }\\n    }\\n\\n     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\\n         print(\\\"deviceToken: @%\\\", deviceToken)\\n         if MOCA.initialized() {\\n             MOCA.registerDeviceToken(deviceToken)\\n         }\\n     }\\n     \\n     func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\\n         print(\\\"remote push notifications registration failed\\\")\\n     }\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"\\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  \\n  // do not forget to #import \\\"MOCA.h\\\"\\n    BOOL mocaStarted = [MOCA initializeSDK];\\n    if (!mocaStarted) {\\n        NSLog(@\\\"Cannot initialize MOCA SDK\\\");\\n    }\\n\\t  // do not forget declare that your AppDelegate conforms with the         UNUserNotificationCenterDelegate protocol\\n    UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];\\n    notificationCenter.delegate = self;\\n\\n    return YES;\\n}\\n\\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\\n       willPresentNotification:(UNNotification *)notification\\n         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {\\n    if (MOCA.initialized && [MOCA isMocaNotification:notification]) {\\n        [MOCA userNotificationCenter:center\\n             willPresentNotification:notification\\n               withCompletionHandler:completionHandler];\\n    }\\n}\\n\\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\\ndidReceiveNotificationResponse:(UNNotificationResponse *)response\\n         withCompletionHandler:(void (^)(void))completionHandler {\\n    if (MOCA.initialized && [MOCA isMocaNotification:response]) {\\n        [MOCA userNotificationCenter:center\\n      didReceiveNotificationResponse:response\\n               withCompletionHandler:completionHandler];\\n    }\\n}\\n\\n- (void)         application:(UIApplication *)application\\ndidReceiveRemoteNotification:(NSDictionary *)userInfo\\n      fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {\\n    if (MOCA.initialized && [MOCA isMocaNotification:userInfo]) {\\n        [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:completionHandler];\\n    }\\n}\\n\\n- (void)                             application:(UIApplication *)application\\ndidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {\\n    NSLog(@\\\"deviceToken: %@\\\", deviceToken);\\n    if ([MOCA initialized]) {\\n    \\t[MOCA registerDeviceToken:deviceToken];\\n    }\\n}\\n\\n- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {\\n    NSLog(@\\\"Failed to get token, error: %@\\\", error);\\n}\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Step by step integration\"\n}\n[/block]\n1 - (Objective-C Only) Import `\"MOCA.h\"` header file into your app’s delegate implementation file.\n\n2 - initialize MOCA SDK is in you app’s delegate `application:didFinishLaunchingWithOptions:` method.\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#import <MOCA.h>\\n\\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\\n{\\n    // Initialize MOCA SDK.\\n    BOOL mocaReady = [MOCA initializeSDK];\\n    if (!mocaReady) {\\n        NSLog(@\\\"MOCA SDK initialization failed.\\\");\\n    }\\n    return YES;\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\\n        let mocaStarted = MOCA.initializeSDK()\\n        if !mocaStarted {\\n            print(\\\"Cannot initialize MOCA SDK\\\")\\n        }\\n        return true\\n    }\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n- You must initialize the SDK before calling any other method.\n\n- On initialization, MOCA SDK will load configuration from MOCAConfig.plist file and perform all necessary framework setup.\n\n- The `[MOCA initializeSDK]` method call returns `YES` on success, and `NO` on error.\n\n3 - Handle local notifications in your AppDelegate:\n\n3.1 - Subscribe to the Notification Center. This is typically done in the AppDelegate. Remember to have only **a single delegate in your app**.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];\\ncenter.delegate = self;\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"let center = UNUserNotificationCenter.current()\\ncenter.delegate = self\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n3.2 - Declare the protocol conformance in your class. Example:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@interface AppDelegate : <UIApplicationDelegate,        UNUserNotificationCenterDelegate>\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"class AppDelegate: ...  UNUserNotificationCenterDelegate \\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n3.3 - Implement the following methods in the class that conforms with the `UNUserNotificationCenterDelegate` protocol:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.\\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\\n       willPresentNotification:(UNNotification *)notification\\n         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {\\n    if(MOCA.initialized && [MOCA isMocaNotification:notification]) {\\n        [MOCA userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler];\\n    }\\n}\\n\\n// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.\\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\\ndidReceiveNotificationResponse:(UNNotificationResponse *)response\\n         withCompletionHandler:(void(^)(void))completionHandler {\\n    if(MOCA.initialized && [MOCA isMocaNotification:response]) {\\n        [MOCA userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler];\\n    }\\n}\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\\n        if(MOCA.initialized() && MOCA.isMocaNotification(notification)) {\\n            MOCA.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)\\n        }\\n\\n    }\\n    \\n    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\\n        if(MOCA.initialized() && MOCA.isMocaNotification(response)) {\\n            MOCA.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)\\n        }\\n    }\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n4 - Integrate with iOS Remote Push Notifications\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler: (void (^)(UIBackgroundFetchResult))completionHandler {\\n   if (MOCA.initialized) {\\n        [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:handler];\\n    }\\n}\\n\\n-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken\\n{\\n    NSLog(@\\\"deviceToken: %@\\\", deviceToken);\\n    if(![MOCA initialized]) {\\n        return;\\n    }\\n   [MOCA registerDeviceToken:deviceToken];\\n}\\n\\n- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\\n{\\n    NSLog(@\\\"Failed to get token, error: %@\\\", error);\\n}\\n\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\\n     if MOCA.initialized() {\\n         MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\\n     }\\n    }\\n\\n     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\\n         print(\\\"deviceToken: @%\\\", deviceToken)\\n         if MOCA.initialized() {\\n             MOCA.registerDeviceToken(deviceToken)\\n         }\\n     }\\n     \\n     func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\\n         print(\\\"remote push notifications registration failed\\\")\\n     }\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"3rd Party SDKs\",\n  \"body\": \"If you are using 3rd party SDKs or your own application makes use of the Remote or Local notifications. Make sure to filter out not MOCA notifications by calling:\\n\\n`[MOCA isMocaNotification:notification]` *Obj-C*\\n`MOCA.isMocaNotification(notification)` *Swift*\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"success\",\n  \"body\": \"At this point, your application is ready to receive MOCA Mobile Engagement campaigns.\\n Go to the [MOCA Console](https://console.mocaplatform.com), create some campaigns and test your MOCA Engagement Experiences.\"\n}\n[/block]","hidden":false,"link_external":false,"next":{"pages":[],"description":""},"sync_unique":"","updates":[],"user":"55a575ebaaf9cf1900114d73","api":{"results":{"codes":[{"status":200,"name":"","code":"{}","language":"json"},{"code":"{}","language":"json","status":400,"name":""}]},"settings":"","auth":"required","params":[],"url":""},"createdAt":"2015-07-15T07:54:08.281Z","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Integration

This section describes how to integrate MOCA iOS SDK with your app code.

[block:api-header] { "title": "\"Show me the code\" Integration" } [/block] [block:code] { "codes": [ { "code": " func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n let mocaStarted = MOCA.initializeSDK()\n if !mocaStarted {\n print(\"Cannot initialize MOCA SDK\")\n }\n let center = UNUserNotificationCenter.current()\n center.delegate = self\n return true\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(notification)) {\n MOCA.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)\n }\n\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(response)) {\n MOCA.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)\n }\n }\n \n func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\n }\n }\n\n func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n print(\"deviceToken: @%\", deviceToken)\n if MOCA.initialized() {\n MOCA.registerDeviceToken(deviceToken)\n }\n }\n \n func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n print(\"remote push notifications registration failed\")\n }", "language": "swift" }, { "code": "\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { \n // do not forget to #import \"MOCA.h\"\n BOOL mocaStarted = [MOCA initializeSDK];\n if (!mocaStarted) {\n NSLog(@\"Cannot initialize MOCA SDK\");\n }\n\t // do not forget declare that your AppDelegate conforms with the UNUserNotificationCenterDelegate protocol\n UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];\n notificationCenter.delegate = self;\n\n return YES;\n}\n\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\n willPresentNotification:(UNNotification *)notification\n withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {\n if (MOCA.initialized && [MOCA isMocaNotification:notification]) {\n [MOCA userNotificationCenter:center\n willPresentNotification:notification\n withCompletionHandler:completionHandler];\n }\n}\n\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\ndidReceiveNotificationResponse:(UNNotificationResponse *)response\n withCompletionHandler:(void (^)(void))completionHandler {\n if (MOCA.initialized && [MOCA isMocaNotification:response]) {\n [MOCA userNotificationCenter:center\n didReceiveNotificationResponse:response\n withCompletionHandler:completionHandler];\n }\n}\n\n- (void) application:(UIApplication *)application\ndidReceiveRemoteNotification:(NSDictionary *)userInfo\n fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {\n if (MOCA.initialized && [MOCA isMocaNotification:userInfo]) {\n [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:completionHandler];\n }\n}\n\n- (void) application:(UIApplication *)application\ndidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {\n NSLog(@\"deviceToken: %@\", deviceToken);\n if ([MOCA initialized]) {\n \t[MOCA registerDeviceToken:deviceToken];\n }\n}\n\n- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {\n NSLog(@\"Failed to get token, error: %@\", error);\n}", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Step by step integration" } [/block] 1 - (Objective-C Only) Import `"MOCA.h"` header file into your app’s delegate implementation file. 2 - initialize MOCA SDK is in you app’s delegate `application:didFinishLaunchingWithOptions:` method. [block:code] { "codes": [ { "code": "#import <MOCA.h>\n\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n // Initialize MOCA SDK.\n BOOL mocaReady = [MOCA initializeSDK];\n if (!mocaReady) {\n NSLog(@\"MOCA SDK initialization failed.\");\n }\n return YES;\n}\n", "language": "objectivec" }, { "code": " func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n let mocaStarted = MOCA.initializeSDK()\n if !mocaStarted {\n print(\"Cannot initialize MOCA SDK\")\n }\n return true\n }", "language": "swift" } ] } [/block] - You must initialize the SDK before calling any other method. - On initialization, MOCA SDK will load configuration from MOCAConfig.plist file and perform all necessary framework setup. - The `[MOCA initializeSDK]` method call returns `YES` on success, and `NO` on error. 3 - Handle local notifications in your AppDelegate: 3.1 - Subscribe to the Notification Center. This is typically done in the AppDelegate. Remember to have only **a single delegate in your app**. [block:code] { "codes": [ { "code": "UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];\ncenter.delegate = self;", "language": "objectivec" }, { "code": "let center = UNUserNotificationCenter.current()\ncenter.delegate = self", "language": "swift" } ] } [/block] 3.2 - Declare the protocol conformance in your class. Example: [block:code] { "codes": [ { "code": "@interface AppDelegate : <UIApplicationDelegate, UNUserNotificationCenterDelegate>", "language": "objectivec" }, { "code": "class AppDelegate: ... UNUserNotificationCenterDelegate \n", "language": "swift" } ] } [/block] 3.3 - Implement the following methods in the class that conforms with the `UNUserNotificationCenterDelegate` protocol: [block:code] { "codes": [ { "code": "// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\n willPresentNotification:(UNNotification *)notification\n withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {\n if(MOCA.initialized && [MOCA isMocaNotification:notification]) {\n [MOCA userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler];\n }\n}\n\n// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\ndidReceiveNotificationResponse:(UNNotificationResponse *)response\n withCompletionHandler:(void(^)(void))completionHandler {\n if(MOCA.initialized && [MOCA isMocaNotification:response]) {\n [MOCA userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler];\n }\n}", "language": "objectivec" }, { "code": " func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(notification)) {\n MOCA.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)\n }\n\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(response)) {\n MOCA.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)\n }\n }", "language": "swift" } ] } [/block] 4 - Integrate with iOS Remote Push Notifications [block:code] { "codes": [ { "code": "-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler: (void (^)(UIBackgroundFetchResult))completionHandler {\n if (MOCA.initialized) {\n [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:handler];\n }\n}\n\n-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken\n{\n NSLog(@\"deviceToken: %@\", deviceToken);\n if(![MOCA initialized]) {\n return;\n }\n [MOCA registerDeviceToken:deviceToken];\n}\n\n- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\n{\n NSLog(@\"Failed to get token, error: %@\", error);\n}\n\n", "language": "objectivec" }, { "code": " func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\n }\n }\n\n func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n print(\"deviceToken: @%\", deviceToken)\n if MOCA.initialized() {\n MOCA.registerDeviceToken(deviceToken)\n }\n }\n \n func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n print(\"remote push notifications registration failed\")\n }", "language": "swift" } ] } [/block] [block:callout] { "type": "danger", "title": "3rd Party SDKs", "body": "If you are using 3rd party SDKs or your own application makes use of the Remote or Local notifications. Make sure to filter out not MOCA notifications by calling:\n\n`[MOCA isMocaNotification:notification]` *Obj-C*\n`MOCA.isMocaNotification(notification)` *Swift*" } [/block] [block:callout] { "type": "success", "body": "At this point, your application is ready to receive MOCA Mobile Engagement campaigns.\n Go to the [MOCA Console](https://console.mocaplatform.com), create some campaigns and test your MOCA Engagement Experiences." } [/block]
[block:api-header] { "title": "\"Show me the code\" Integration" } [/block] [block:code] { "codes": [ { "code": " func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n let mocaStarted = MOCA.initializeSDK()\n if !mocaStarted {\n print(\"Cannot initialize MOCA SDK\")\n }\n let center = UNUserNotificationCenter.current()\n center.delegate = self\n return true\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(notification)) {\n MOCA.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)\n }\n\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(response)) {\n MOCA.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)\n }\n }\n \n func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\n }\n }\n\n func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n print(\"deviceToken: @%\", deviceToken)\n if MOCA.initialized() {\n MOCA.registerDeviceToken(deviceToken)\n }\n }\n \n func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n print(\"remote push notifications registration failed\")\n }", "language": "swift" }, { "code": "\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { \n // do not forget to #import \"MOCA.h\"\n BOOL mocaStarted = [MOCA initializeSDK];\n if (!mocaStarted) {\n NSLog(@\"Cannot initialize MOCA SDK\");\n }\n\t // do not forget declare that your AppDelegate conforms with the UNUserNotificationCenterDelegate protocol\n UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];\n notificationCenter.delegate = self;\n\n return YES;\n}\n\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\n willPresentNotification:(UNNotification *)notification\n withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {\n if (MOCA.initialized && [MOCA isMocaNotification:notification]) {\n [MOCA userNotificationCenter:center\n willPresentNotification:notification\n withCompletionHandler:completionHandler];\n }\n}\n\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\ndidReceiveNotificationResponse:(UNNotificationResponse *)response\n withCompletionHandler:(void (^)(void))completionHandler {\n if (MOCA.initialized && [MOCA isMocaNotification:response]) {\n [MOCA userNotificationCenter:center\n didReceiveNotificationResponse:response\n withCompletionHandler:completionHandler];\n }\n}\n\n- (void) application:(UIApplication *)application\ndidReceiveRemoteNotification:(NSDictionary *)userInfo\n fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {\n if (MOCA.initialized && [MOCA isMocaNotification:userInfo]) {\n [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:completionHandler];\n }\n}\n\n- (void) application:(UIApplication *)application\ndidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {\n NSLog(@\"deviceToken: %@\", deviceToken);\n if ([MOCA initialized]) {\n \t[MOCA registerDeviceToken:deviceToken];\n }\n}\n\n- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {\n NSLog(@\"Failed to get token, error: %@\", error);\n}", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Step by step integration" } [/block] 1 - (Objective-C Only) Import `"MOCA.h"` header file into your app’s delegate implementation file. 2 - initialize MOCA SDK is in you app’s delegate `application:didFinishLaunchingWithOptions:` method. [block:code] { "codes": [ { "code": "#import <MOCA.h>\n\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n // Initialize MOCA SDK.\n BOOL mocaReady = [MOCA initializeSDK];\n if (!mocaReady) {\n NSLog(@\"MOCA SDK initialization failed.\");\n }\n return YES;\n}\n", "language": "objectivec" }, { "code": " func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n let mocaStarted = MOCA.initializeSDK()\n if !mocaStarted {\n print(\"Cannot initialize MOCA SDK\")\n }\n return true\n }", "language": "swift" } ] } [/block] - You must initialize the SDK before calling any other method. - On initialization, MOCA SDK will load configuration from MOCAConfig.plist file and perform all necessary framework setup. - The `[MOCA initializeSDK]` method call returns `YES` on success, and `NO` on error. 3 - Handle local notifications in your AppDelegate: 3.1 - Subscribe to the Notification Center. This is typically done in the AppDelegate. Remember to have only **a single delegate in your app**. [block:code] { "codes": [ { "code": "UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];\ncenter.delegate = self;", "language": "objectivec" }, { "code": "let center = UNUserNotificationCenter.current()\ncenter.delegate = self", "language": "swift" } ] } [/block] 3.2 - Declare the protocol conformance in your class. Example: [block:code] { "codes": [ { "code": "@interface AppDelegate : <UIApplicationDelegate, UNUserNotificationCenterDelegate>", "language": "objectivec" }, { "code": "class AppDelegate: ... UNUserNotificationCenterDelegate \n", "language": "swift" } ] } [/block] 3.3 - Implement the following methods in the class that conforms with the `UNUserNotificationCenterDelegate` protocol: [block:code] { "codes": [ { "code": "// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\n willPresentNotification:(UNNotification *)notification\n withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {\n if(MOCA.initialized && [MOCA isMocaNotification:notification]) {\n [MOCA userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler];\n }\n}\n\n// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.\n- (void)userNotificationCenter:(UNUserNotificationCenter *)center\ndidReceiveNotificationResponse:(UNNotificationResponse *)response\n withCompletionHandler:(void(^)(void))completionHandler {\n if(MOCA.initialized && [MOCA isMocaNotification:response]) {\n [MOCA userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler];\n }\n}", "language": "objectivec" }, { "code": " func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(notification)) {\n MOCA.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)\n }\n\n }\n \n func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {\n if(MOCA.initialized() && MOCA.isMocaNotification(response)) {\n MOCA.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler)\n }\n }", "language": "swift" } ] } [/block] 4 - Integrate with iOS Remote Push Notifications [block:code] { "codes": [ { "code": "-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler: (void (^)(UIBackgroundFetchResult))completionHandler {\n if (MOCA.initialized) {\n [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:handler];\n }\n}\n\n-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken\n{\n NSLog(@\"deviceToken: %@\", deviceToken);\n if(![MOCA initialized]) {\n return;\n }\n [MOCA registerDeviceToken:deviceToken];\n}\n\n- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\n{\n NSLog(@\"Failed to get token, error: %@\", error);\n}\n\n", "language": "objectivec" }, { "code": " func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\n }\n }\n\n func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n print(\"deviceToken: @%\", deviceToken)\n if MOCA.initialized() {\n MOCA.registerDeviceToken(deviceToken)\n }\n }\n \n func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n print(\"remote push notifications registration failed\")\n }", "language": "swift" } ] } [/block] [block:callout] { "type": "danger", "title": "3rd Party SDKs", "body": "If you are using 3rd party SDKs or your own application makes use of the Remote or Local notifications. Make sure to filter out not MOCA notifications by calling:\n\n`[MOCA isMocaNotification:notification]` *Obj-C*\n`MOCA.isMocaNotification(notification)` *Swift*" } [/block] [block:callout] { "type": "success", "body": "At this point, your application is ready to receive MOCA Mobile Engagement campaigns.\n Go to the [MOCA Console](https://console.mocaplatform.com), create some campaigns and test your MOCA Engagement Experiences." } [/block]
{"_id":"5f998577fb81e800451c02fe","hidden":false,"parentDoc":null,"category":"5f998576fb81e800451c02f3","createdAt":"2015-07-14T22:50:05.314Z","githubsync":"","sync_unique":"","title":"Submitting Your App to the Store","updates":[],"user":"55a575ebaaf9cf1900114d73","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"status":200,"name":"","code":"{}","language":"json"},{"name":"","code":"{}","language":"json","status":400}]}},"link_url":"","slug":"moca-ios-sdk-submitting-your-app-to-the-store","order":4,"type":"basic","version":"5f998577fb81e800451c032f","__v":0,"next":{"pages":[],"description":""},"link_external":false,"project":"559a61d2dbcfd20d00710b39","body":"Congratulations! After all the hard work you are finally ready to ship your app.\nLet's review the following checklist, just to be sure everything goes smoothly.\n\n- Ensure your `App Key` and `App Secret` are pointing to your production App.\n- Change the log level in the `MOCAConfig.plist` / `AndroidManifest.xml` of your app to `info`, instead of `debug`.\n- Ensure no *test* campaigns are active in the production App.\n\n##Uploading to iTunes Connect\n\n###App Review Information\n\nMOCA SDK uses certain iOS features that need to be explained one by one to the Apple AppStore review team. When submitting app, include the following link in the \"Notes\" section of the \"App Review Information\": \n\n[Notes for AppStore review team](../page/moca-sdk-notes-for-appstore-review-team)  \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"http://developer.mocaplatform.com/v1.0/page/moca-sdk-notes-for-appstore-review-team\",\n      \"language\": \"text\"\n    }\n  ]\n}\n[/block]\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/de3WTBBeT4y9wXRj2sAx_notes.png\",\n        \"notes.png\",\n        \"967\",\n        \"281\",\n        \"#dddddd\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"success\",\n  \"title\": \"Avoid App Rejections\",\n  \"body\": \"By including this information in your app description, you will lower the chance of being rejected by the AppStore review team.\"\n}\n[/block]","excerpt":"","isReference":false,"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Submitting Your App to the Store


Congratulations! After all the hard work you are finally ready to ship your app. Let's review the following checklist, just to be sure everything goes smoothly. - Ensure your `App Key` and `App Secret` are pointing to your production App. - Change the log level in the `MOCAConfig.plist` / `AndroidManifest.xml` of your app to `info`, instead of `debug`. - Ensure no *test* campaigns are active in the production App. ##Uploading to iTunes Connect ###App Review Information MOCA SDK uses certain iOS features that need to be explained one by one to the Apple AppStore review team. When submitting app, include the following link in the "Notes" section of the "App Review Information": [Notes for AppStore review team](../page/moca-sdk-notes-for-appstore-review-team) [block:code] { "codes": [ { "code": "http://developer.mocaplatform.com/v1.0/page/moca-sdk-notes-for-appstore-review-team", "language": "text" } ] } [/block] [block:image] { "images": [ { "image": [ "https://files.readme.io/de3WTBBeT4y9wXRj2sAx_notes.png", "notes.png", "967", "281", "#dddddd", "" ] } ] } [/block] [block:callout] { "type": "success", "title": "Avoid App Rejections", "body": "By including this information in your app description, you will lower the chance of being rejected by the AppStore review team." } [/block]
Congratulations! After all the hard work you are finally ready to ship your app. Let's review the following checklist, just to be sure everything goes smoothly. - Ensure your `App Key` and `App Secret` are pointing to your production App. - Change the log level in the `MOCAConfig.plist` / `AndroidManifest.xml` of your app to `info`, instead of `debug`. - Ensure no *test* campaigns are active in the production App. ##Uploading to iTunes Connect ###App Review Information MOCA SDK uses certain iOS features that need to be explained one by one to the Apple AppStore review team. When submitting app, include the following link in the "Notes" section of the "App Review Information": [Notes for AppStore review team](../page/moca-sdk-notes-for-appstore-review-team) [block:code] { "codes": [ { "code": "http://developer.mocaplatform.com/v1.0/page/moca-sdk-notes-for-appstore-review-team", "language": "text" } ] } [/block] [block:image] { "images": [ { "image": [ "https://files.readme.io/de3WTBBeT4y9wXRj2sAx_notes.png", "notes.png", "967", "281", "#dddddd", "" ] } ] } [/block] [block:callout] { "type": "success", "title": "Avoid App Rejections", "body": "By including this information in your app description, you will lower the chance of being rejected by the AppStore review team." } [/block]
{"_id":"5f998577fb81e800451c02ff","slug":"remote-push-notifications-apns-setup","updates":[],"body":"MOCA Platform uses [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS) to deliver notifications to your iOS users. Please bear in mind this is only for remote push notifications, and **this is not mandatory for location based notifications** (Proximity Experiences).\n\n\n###Before starting\n\nIn order to get the certificates and upload them to MOCA, you will need:\n\n- A membership in the [Apple iOS developer program](https://developer.apple.com/programs/)\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Enable Remote Push Notifications on your App ID\"\n}\n[/block]\n- Sign in to your account in the [Apple developer center](https://developer.apple.com/account/\n), and then go to **Certificates, Identifiers & Profiles**\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/444df5c-CertsIdentiProfs.png\",\n        \"CertsIdentiProfs.png\",\n        707,\n        298,\n        \"#fbfbfb\"\n      ]\n    }\n  ]\n}\n[/block]\n- Each App should have an App ID, click the App ID that corresponds to your App (or create it if you have not already done so). In any case, ensure that the Push Notifications service is enabled.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/6a1106c-APNS_on.png\",\n        \"APNS_on.png\",\n        635,\n        696,\n        \"#3f4241\"\n      ]\n    }\n  ]\n}\n[/block]\n- Click on the `Development` or `Production` certificate button and follow the steps.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Exporting certificates\"\n}\n[/block]\n- Open the `KeyChain Access` App of your Mac, there you will find the certificates that you downloaded in the previous step.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"This application may have different names depending on your Mac language configuration:\",\n  \"body\": \"Català: “Accés a clauers”\\nEspañol: \\\"Acceso a llaveros\\\"\\nFrançais: \\\"Trousseau d'accès\\\"\\nPortuguês: \\\"Acesso às Chaves\\\"\"\n}\n[/block]\n- Right click on the certificate, and select \"Export ....\". Select the `p12` format and create a password for the file, do not lose this password as you will need it a next step.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/462ecb2-keychain_access.png\",\n        \"keychain_access.png\",\n        662,\n        364,\n        \"#eeeeed\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Production vs Development\",\n  \"body\": \"Ensure that the App in MOCA Console is pointing to the right servers. Production certificates won't work for Development apps and vice versa.\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Warning\",\n  \"body\": \"Do not submit Apps to Apple with Development certificates.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Uploading the certificates to MOCA Console\"\n}\n[/block]\n- Login in to your MOCA Account, and go to Apps **>** *app_to_be_configured* ** >** Settings **>** Services\n- Upload the file using the Add button in the \"APNS\" section, you will need the password you created in a previous step.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/791a0f6-APNS_upload.png\",\n        \"APNS_upload.png\",\n        778,\n        669,\n        \"#efefed\"\n      ]\n    }\n  ]\n}\n[/block]\n- All done. You can now start sending notifications to your users using MOCA Platform.","hidden":false,"link_external":false,"next":{"pages":[],"description":""},"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","createdAt":"2016-07-25T13:28:32.384Z","githubsync":"","type":"basic","user":"559a618bdbcfd20d00710b38","title":"APNS: Certificates for push notifications","version":"5f998577fb81e800451c032f","api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"category":"5f998576fb81e800451c02f3","excerpt":"","isReference":false,"link_url":"","sync_unique":"","__v":0,"order":5,"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

APNS: Certificates for push notifications


MOCA Platform uses [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS) to deliver notifications to your iOS users. Please bear in mind this is only for remote push notifications, and **this is not mandatory for location based notifications** (Proximity Experiences). ###Before starting In order to get the certificates and upload them to MOCA, you will need: - A membership in the [Apple iOS developer program](https://developer.apple.com/programs/) [block:api-header] { "type": "basic", "title": "Enable Remote Push Notifications on your App ID" } [/block] - Sign in to your account in the [Apple developer center](https://developer.apple.com/account/ ), and then go to **Certificates, Identifiers & Profiles** [block:image] { "images": [ { "image": [ "https://files.readme.io/444df5c-CertsIdentiProfs.png", "CertsIdentiProfs.png", 707, 298, "#fbfbfb" ] } ] } [/block] - Each App should have an App ID, click the App ID that corresponds to your App (or create it if you have not already done so). In any case, ensure that the Push Notifications service is enabled. [block:image] { "images": [ { "image": [ "https://files.readme.io/6a1106c-APNS_on.png", "APNS_on.png", 635, 696, "#3f4241" ] } ] } [/block] - Click on the `Development` or `Production` certificate button and follow the steps. [block:api-header] { "type": "basic", "title": "Exporting certificates" } [/block] - Open the `KeyChain Access` App of your Mac, there you will find the certificates that you downloaded in the previous step. [block:callout] { "type": "info", "title": "This application may have different names depending on your Mac language configuration:", "body": "Català: “Accés a clauers”\nEspañol: \"Acceso a llaveros\"\nFrançais: \"Trousseau d'accès\"\nPortuguês: \"Acesso às Chaves\"" } [/block] - Right click on the certificate, and select "Export ....". Select the `p12` format and create a password for the file, do not lose this password as you will need it a next step. [block:image] { "images": [ { "image": [ "https://files.readme.io/462ecb2-keychain_access.png", "keychain_access.png", 662, 364, "#eeeeed" ] } ] } [/block] [block:callout] { "type": "danger", "title": "Production vs Development", "body": "Ensure that the App in MOCA Console is pointing to the right servers. Production certificates won't work for Development apps and vice versa." } [/block] [block:callout] { "type": "warning", "title": "Warning", "body": "Do not submit Apps to Apple with Development certificates." } [/block] [block:api-header] { "type": "basic", "title": "Uploading the certificates to MOCA Console" } [/block] - Login in to your MOCA Account, and go to Apps **>** *app_to_be_configured* ** >** Settings **>** Services - Upload the file using the Add button in the "APNS" section, you will need the password you created in a previous step. [block:image] { "images": [ { "image": [ "https://files.readme.io/791a0f6-APNS_upload.png", "APNS_upload.png", 778, 669, "#efefed" ] } ] } [/block] - All done. You can now start sending notifications to your users using MOCA Platform.
MOCA Platform uses [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS) to deliver notifications to your iOS users. Please bear in mind this is only for remote push notifications, and **this is not mandatory for location based notifications** (Proximity Experiences). ###Before starting In order to get the certificates and upload them to MOCA, you will need: - A membership in the [Apple iOS developer program](https://developer.apple.com/programs/) [block:api-header] { "type": "basic", "title": "Enable Remote Push Notifications on your App ID" } [/block] - Sign in to your account in the [Apple developer center](https://developer.apple.com/account/ ), and then go to **Certificates, Identifiers & Profiles** [block:image] { "images": [ { "image": [ "https://files.readme.io/444df5c-CertsIdentiProfs.png", "CertsIdentiProfs.png", 707, 298, "#fbfbfb" ] } ] } [/block] - Each App should have an App ID, click the App ID that corresponds to your App (or create it if you have not already done so). In any case, ensure that the Push Notifications service is enabled. [block:image] { "images": [ { "image": [ "https://files.readme.io/6a1106c-APNS_on.png", "APNS_on.png", 635, 696, "#3f4241" ] } ] } [/block] - Click on the `Development` or `Production` certificate button and follow the steps. [block:api-header] { "type": "basic", "title": "Exporting certificates" } [/block] - Open the `KeyChain Access` App of your Mac, there you will find the certificates that you downloaded in the previous step. [block:callout] { "type": "info", "title": "This application may have different names depending on your Mac language configuration:", "body": "Català: “Accés a clauers”\nEspañol: \"Acceso a llaveros\"\nFrançais: \"Trousseau d'accès\"\nPortuguês: \"Acesso às Chaves\"" } [/block] - Right click on the certificate, and select "Export ....". Select the `p12` format and create a password for the file, do not lose this password as you will need it a next step. [block:image] { "images": [ { "image": [ "https://files.readme.io/462ecb2-keychain_access.png", "keychain_access.png", 662, 364, "#eeeeed" ] } ] } [/block] [block:callout] { "type": "danger", "title": "Production vs Development", "body": "Ensure that the App in MOCA Console is pointing to the right servers. Production certificates won't work for Development apps and vice versa." } [/block] [block:callout] { "type": "warning", "title": "Warning", "body": "Do not submit Apps to Apple with Development certificates." } [/block] [block:api-header] { "type": "basic", "title": "Uploading the certificates to MOCA Console" } [/block] - Login in to your MOCA Account, and go to Apps **>** *app_to_be_configured* ** >** Settings **>** Services - Upload the file using the Add button in the "APNS" section, you will need the password you created in a previous step. [block:image] { "images": [ { "image": [ "https://files.readme.io/791a0f6-APNS_upload.png", "APNS_upload.png", 778, 669, "#efefed" ] } ] } [/block] - All done. You can now start sending notifications to your users using MOCA Platform.
{"_id":"5f99ab32c37577005b26a076","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Additional settings","type":"basic","slug":"additional-settings","excerpt":"","body":"[block:api-header]\n{\n  \"title\": \"Mute notifications\"\n}\n[/block]\nIf for any reason you want to mute the MOCA generated notifications (for example by adding a switch within your application settings). Call the following method\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.muteNotifications(true)\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA muteNotifications:YES];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\nThis setting is persisted between app restarts. In order to restore the SDK to its normal state, call the same method with a `false` / `NO` argument.\n\nIn order to check the status of this setting, call:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.areNotificationsMuted()\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA areNotificationsMuted];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Geofence and beacon detection\"\n}\n[/block]\nCall the following method with the correct argument in order to enable or disable geofences and bluetooth beacon detection.\n\n- `true`/``YES`: Enables the feature.\n- `false`/``NO`: Disables the feature.\nThis setting is persisted across app restarts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setProximityEnabled(true)\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA setProximityEnabled:YES]\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Geolocation tracking\"\n}\n[/block]\nWhen disabled, this prevents the SDK from sending user locations for Analytics\n\n- `true`/``YES`: Enables the feature.\n- `false`/``NO`: Disables the feature.\nThis setting is persisted across app restarts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setGeoTrackingEnabled(true)\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA setGeoTrackingEnabled:YES];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Wi-Fi Only data synchronization\"\n}\n[/block]\nWhen active, this setting prevents the SDK from downloading and uploading data when using cellular data. This is useful if your application \n\n- `true`/``YES`: Enables the feature.\n- `false`/``NO`: Disables the feature.\nThis setting is persisted across app restarts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" MOCA.setWifiOnlyEnabled(true)\\n\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA setWifiOnlyEnabled:YES];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","updates":[],"order":6,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-10-28T17:32:34.678Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Additional settings


[block:api-header] { "title": "Mute notifications" } [/block] If for any reason you want to mute the MOCA generated notifications (for example by adding a switch within your application settings). Call the following method [block:code] { "codes": [ { "code": "MOCA.muteNotifications(true)", "language": "swift" }, { "code": "[MOCA muteNotifications:YES];", "language": "objectivec" } ] } [/block] This setting is persisted between app restarts. In order to restore the SDK to its normal state, call the same method with a `false` / `NO` argument. In order to check the status of this setting, call: [block:code] { "codes": [ { "code": "MOCA.areNotificationsMuted()", "language": "swift" }, { "code": "[MOCA areNotificationsMuted];", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Geofence and beacon detection" } [/block] Call the following method with the correct argument in order to enable or disable geofences and bluetooth beacon detection. - `true`/``YES`: Enables the feature. - `false`/``NO`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setProximityEnabled(true)", "language": "swift" }, { "code": "[MOCA setProximityEnabled:YES]", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Geolocation tracking" } [/block] When disabled, this prevents the SDK from sending user locations for Analytics - `true`/``YES`: Enables the feature. - `false`/``NO`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true)", "language": "swift" }, { "code": "[MOCA setGeoTrackingEnabled:YES];", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Wi-Fi Only data synchronization" } [/block] When active, this setting prevents the SDK from downloading and uploading data when using cellular data. This is useful if your application - `true`/``YES`: Enables the feature. - `false`/``NO`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": " MOCA.setWifiOnlyEnabled(true)\n", "language": "swift" }, { "code": "[MOCA setWifiOnlyEnabled:YES];", "language": "objectivec" } ] } [/block]
[block:api-header] { "title": "Mute notifications" } [/block] If for any reason you want to mute the MOCA generated notifications (for example by adding a switch within your application settings). Call the following method [block:code] { "codes": [ { "code": "MOCA.muteNotifications(true)", "language": "swift" }, { "code": "[MOCA muteNotifications:YES];", "language": "objectivec" } ] } [/block] This setting is persisted between app restarts. In order to restore the SDK to its normal state, call the same method with a `false` / `NO` argument. In order to check the status of this setting, call: [block:code] { "codes": [ { "code": "MOCA.areNotificationsMuted()", "language": "swift" }, { "code": "[MOCA areNotificationsMuted];", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Geofence and beacon detection" } [/block] Call the following method with the correct argument in order to enable or disable geofences and bluetooth beacon detection. - `true`/``YES`: Enables the feature. - `false`/``NO`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setProximityEnabled(true)", "language": "swift" }, { "code": "[MOCA setProximityEnabled:YES]", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Geolocation tracking" } [/block] When disabled, this prevents the SDK from sending user locations for Analytics - `true`/``YES`: Enables the feature. - `false`/``NO`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true)", "language": "swift" }, { "code": "[MOCA setGeoTrackingEnabled:YES];", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Wi-Fi Only data synchronization" } [/block] When active, this setting prevents the SDK from downloading and uploading data when using cellular data. This is useful if your application - `true`/``YES`: Enables the feature. - `false`/``NO`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": " MOCA.setWifiOnlyEnabled(true)\n", "language": "swift" }, { "code": "[MOCA setWifiOnlyEnabled:YES];", "language": "objectivec" } ] } [/block]
{"_id":"5f998577fb81e800451c0301","api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required"},"category":"5f998576fb81e800451c02f3","parentDoc":null,"sync_unique":"","updates":[],"user":"559a618bdbcfd20d00710b38","isReference":false,"order":7,"project":"559a61d2dbcfd20d00710b39","slug":"instance-api","__v":0,"githubsync":"","hidden":false,"next":{"pages":[],"description":""},"title":"Instance API","type":"basic","createdAt":"2015-07-17T13:10:11.115Z","excerpt":"","link_external":false,"link_url":"","version":"5f998577fb81e800451c032f","body":"- The app `Instance object` is a local representation of an app instance downloaded and installed in a user device. \n- The instance object is **automatically managed** by MOCA. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var theInstance = MOCA.currentInstance()\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"MOCAInstance * theInstance = [MOCA currentInstance];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n- The instance object holds a **collection of properties**. Property-value pairs can be set and retrieved and are persisted between app sessions.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n * Sets the value for the given property name.\\n * \\n * @param value Value to be set. It must belong to one of the accepted classes.\\n * @param prop Property name.\\n */\\n func setValue(_ value: Any!, forProperty property: String!)\\n /**\\n * Gets the value for the given property.\\n *\\n * @param prop Property name.\\n * @return Value associated with the property or <code>nil</code> if none.\\n */\\n  func value(forProperty property: String!) -> Any\\n \\n /**\\n * Returns a new array containing all existing property names.\\n *\\n * @return A new array containing all existing property names.\\n */\\n func allProperties() -> [Any] \",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"/**\\n * Sets the value for the given property name.\\n * \\n * @param value Value to be set. It must belong to one of the accepted classes.\\n * @param prop Property name.\\n */\\n- (void) setValue:(id)value forProperty:(NSString*)prop;\\n\\n/**\\n * Gets the value for the given property.\\n *\\n * @param prop Property name.\\n * @return Value associated with the property or <code>nil</code> if none.\\n */\\n- (id) valueForProperty:(NSString*)prop;\\n\\n/**\\n * Returns a new array containing all existing property names.\\n *\\n * @return A new array containing all existing property names.\\n */\\n- (NSArray*) allProperties;\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n- Each instance object is persisted both locally and in the cloud. The instance is automatically uploaded to the cloud each time the app starts.\n- The instance can be saved manually to the cloud. All saves are asynchronous.\n- It is recommended to perform as many sets as desired and then just invoke a single save operation.\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"let theInstance = MOCA.currentInstance()\\ntheInstance?.setValue(\\\"red\\\", forProperty: \\\"favorite-color\\\")\\ntheInstance?.setValue(\\\"women-cloth\\\", forProperty: \\\"last-search\\\")\\n// Asynchronously save the instance to the cloud.\\ntheInstance?.save({\\n  (_ instance: MOCAInstance?, _ error: Error?) -> Void in\\n  if (error != nil)  {\\n    print(\\\"Save instance failed: (%@)\\\", error ?? \\\"Error not available\\\")\\n  }\\n})\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"#import <AdSupport/ASIdentifierManager.h>\\u000b\\n\\nMOCAInstance * theInstance = [MOCA currentInstance];    \\nif (theInstance)\\n{\\n    // Only track Advertising Identifier, if you app uses explicit Ad banners. \\n    NSString * adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; \\n    [theInstance setValue:adId forProperty:@”_ad_id\\\"];\\n    [theInstance setValue:@\\\"red\\\" forProperty:@\\\"favorite-color\\\"];\\n    [theInstance setValue:@\\\"women-cloth\\\" forKey:@\\\"last-search\\\"];\\u000b    // Asynchronously save the instance to the cloud.\\n    [theInstance saveWithBlock:^(MOCAInstance *instance, NSError *error)\\n        {\\n          if (error) NSLog(@\\\"Save instance failed: %@\\\", error);\\n        }\\n    ];\\n}\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Instance API


- The app `Instance object` is a local representation of an app instance downloaded and installed in a user device. - The instance object is **automatically managed** by MOCA. [block:code] { "codes": [ { "code": "var theInstance = MOCA.currentInstance()", "language": "swift" }, { "code": "MOCAInstance * theInstance = [MOCA currentInstance];", "language": "objectivec" } ] } [/block] - The instance object holds a **collection of properties**. Property-value pairs can be set and retrieved and are persisted between app sessions. [block:code] { "codes": [ { "code": "/**\n * Sets the value for the given property name.\n * \n * @param value Value to be set. It must belong to one of the accepted classes.\n * @param prop Property name.\n */\n func setValue(_ value: Any!, forProperty property: String!)\n /**\n * Gets the value for the given property.\n *\n * @param prop Property name.\n * @return Value associated with the property or <code>nil</code> if none.\n */\n func value(forProperty property: String!) -> Any\n \n /**\n * Returns a new array containing all existing property names.\n *\n * @return A new array containing all existing property names.\n */\n func allProperties() -> [Any] ", "language": "swift" }, { "code": "/**\n * Sets the value for the given property name.\n * \n * @param value Value to be set. It must belong to one of the accepted classes.\n * @param prop Property name.\n */\n- (void) setValue:(id)value forProperty:(NSString*)prop;\n\n/**\n * Gets the value for the given property.\n *\n * @param prop Property name.\n * @return Value associated with the property or <code>nil</code> if none.\n */\n- (id) valueForProperty:(NSString*)prop;\n\n/**\n * Returns a new array containing all existing property names.\n *\n * @return A new array containing all existing property names.\n */\n- (NSArray*) allProperties;", "language": "objectivec" } ] } [/block] - Each instance object is persisted both locally and in the cloud. The instance is automatically uploaded to the cloud each time the app starts. - The instance can be saved manually to the cloud. All saves are asynchronous. - It is recommended to perform as many sets as desired and then just invoke a single save operation. [block:code] { "codes": [ { "code": "let theInstance = MOCA.currentInstance()\ntheInstance?.setValue(\"red\", forProperty: \"favorite-color\")\ntheInstance?.setValue(\"women-cloth\", forProperty: \"last-search\")\n// Asynchronously save the instance to the cloud.\ntheInstance?.save({\n (_ instance: MOCAInstance?, _ error: Error?) -> Void in\n if (error != nil) {\n print(\"Save instance failed: (%@)\", error ?? \"Error not available\")\n }\n})", "language": "swift" }, { "code": "#import <AdSupport/ASIdentifierManager.h>\u000b\n\nMOCAInstance * theInstance = [MOCA currentInstance]; \nif (theInstance)\n{\n // Only track Advertising Identifier, if you app uses explicit Ad banners. \n NSString * adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; \n [theInstance setValue:adId forProperty:@”_ad_id\"];\n [theInstance setValue:@\"red\" forProperty:@\"favorite-color\"];\n [theInstance setValue:@\"women-cloth\" forKey:@\"last-search\"];\u000b // Asynchronously save the instance to the cloud.\n [theInstance saveWithBlock:^(MOCAInstance *instance, NSError *error)\n {\n if (error) NSLog(@\"Save instance failed: %@\", error);\n }\n ];\n}\n", "language": "objectivec" } ] } [/block]
- The app `Instance object` is a local representation of an app instance downloaded and installed in a user device. - The instance object is **automatically managed** by MOCA. [block:code] { "codes": [ { "code": "var theInstance = MOCA.currentInstance()", "language": "swift" }, { "code": "MOCAInstance * theInstance = [MOCA currentInstance];", "language": "objectivec" } ] } [/block] - The instance object holds a **collection of properties**. Property-value pairs can be set and retrieved and are persisted between app sessions. [block:code] { "codes": [ { "code": "/**\n * Sets the value for the given property name.\n * \n * @param value Value to be set. It must belong to one of the accepted classes.\n * @param prop Property name.\n */\n func setValue(_ value: Any!, forProperty property: String!)\n /**\n * Gets the value for the given property.\n *\n * @param prop Property name.\n * @return Value associated with the property or <code>nil</code> if none.\n */\n func value(forProperty property: String!) -> Any\n \n /**\n * Returns a new array containing all existing property names.\n *\n * @return A new array containing all existing property names.\n */\n func allProperties() -> [Any] ", "language": "swift" }, { "code": "/**\n * Sets the value for the given property name.\n * \n * @param value Value to be set. It must belong to one of the accepted classes.\n * @param prop Property name.\n */\n- (void) setValue:(id)value forProperty:(NSString*)prop;\n\n/**\n * Gets the value for the given property.\n *\n * @param prop Property name.\n * @return Value associated with the property or <code>nil</code> if none.\n */\n- (id) valueForProperty:(NSString*)prop;\n\n/**\n * Returns a new array containing all existing property names.\n *\n * @return A new array containing all existing property names.\n */\n- (NSArray*) allProperties;", "language": "objectivec" } ] } [/block] - Each instance object is persisted both locally and in the cloud. The instance is automatically uploaded to the cloud each time the app starts. - The instance can be saved manually to the cloud. All saves are asynchronous. - It is recommended to perform as many sets as desired and then just invoke a single save operation. [block:code] { "codes": [ { "code": "let theInstance = MOCA.currentInstance()\ntheInstance?.setValue(\"red\", forProperty: \"favorite-color\")\ntheInstance?.setValue(\"women-cloth\", forProperty: \"last-search\")\n// Asynchronously save the instance to the cloud.\ntheInstance?.save({\n (_ instance: MOCAInstance?, _ error: Error?) -> Void in\n if (error != nil) {\n print(\"Save instance failed: (%@)\", error ?? \"Error not available\")\n }\n})", "language": "swift" }, { "code": "#import <AdSupport/ASIdentifierManager.h>\u000b\n\nMOCAInstance * theInstance = [MOCA currentInstance]; \nif (theInstance)\n{\n // Only track Advertising Identifier, if you app uses explicit Ad banners. \n NSString * adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; \n [theInstance setValue:adId forProperty:@”_ad_id\"];\n [theInstance setValue:@\"red\" forProperty:@\"favorite-color\"];\n [theInstance setValue:@\"women-cloth\" forKey:@\"last-search\"];\u000b // Asynchronously save the instance to the cloud.\n [theInstance saveWithBlock:^(MOCAInstance *instance, NSError *error)\n {\n if (error) NSLog(@\"Save instance failed: %@\", error);\n }\n ];\n}\n", "language": "objectivec" } ] } [/block]
{"_id":"5f998577fb81e800451c0302","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]}},"body":"- The app **User object** manages information about current application user.\n- This object is **optional**, and it is used when the app needs to authenticate the user. \n- The authentication provides data about user’s identity: a unique user ID or similar. \n- The user login and logout calls are managed by the app. \u000b\n\n - To access existing User object, use currentUser property: \u000b\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"let theUser: MOCAUser? = MOCA.currentInstance().currentUser\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"// Access authenticated user object\\nMOCAUser * theUser = [[MOCA currentInstance] currentUser];\\nif (theUser)\\n{\\n    // ...\\n}\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n- To authenticate a new user, use *login:id* call:\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"User will stay \\\"Logged in\\\" in MOCA SDK until you explicitly call the logout method\",\n  \"title\": \"User will persist across restarts\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"let user = MOCA.currentInstance().login(\\\"[email protected]\\\")\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"MOCAUser * currentUser = [[MOCA currentInstance] login:@\\\"UNIQUE_USER_ID\\\"];\\nif (!currentUser) {\\n   NSLog(@\\\"MOCA User login failed\\\");\\n}\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n- To logout a user, call:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"user.logout()\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[user logout];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n- The user object holds a collection of properties. Property-value pairs can be set and retrieved.\n- Each user object is persisted both locally and in the cloud. \n- It is recommended to perform as many sets as desired and then \njust invoke a single save operation to persist them to the MOCA cloud.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"guard let user = MOCA.currentUser() else {\\n  print(\\\"MOCA User login failed\\\")\\n  return;\\n}\\nuser.setValue(\\\"male\\\", forProperty: \\\"gender\\\")\\nuser.setValue(Int(1975), forProperty: \\\"birth_year\\\")\\n// Asynchronously save the user object to the cloud.\\nuser.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\\n           if error != nil {\\n             print(\\\"Save user failed: (%@)\\\", error ?? \\\"Error not available\\\")\\n           }\\n          })\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"MOCAUser * theUser = [[MOCA currentInstance] currentUser];    \\nif (theUser) {\\n    [theUser setValue:@\\\"male\\\" forProperty:@\\\"gender\\\"];\\n    [theUser setValue:[NSNumber numberWithInt:1975] forProperty:@\\\"birth_year\\\"];    // Asynchronously save the user object to the cloud.\\n    [theUser saveWithBlock:^(MOCAUser *user, NSError *error)\\n        {\\n          if (error) NSLog(@\\\"Save user failed: %@\\\", error);\\n        }\\n    ];\\n}\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","hidden":false,"project":"559a61d2dbcfd20d00710b39","slug":"user-api","createdAt":"2015-07-17T13:24:37.208Z","githubsync":"","isReference":false,"sync_unique":"","title":"User API","updates":[],"user":"559a618bdbcfd20d00710b38","version":"5f998577fb81e800451c032f","__v":0,"excerpt":"","next":{"pages":[],"description":""},"order":8,"type":"basic","category":"5f998576fb81e800451c02f3","link_external":false,"link_url":"","parentDoc":null,"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

User API


- The app **User object** manages information about current application user. - This object is **optional**, and it is used when the app needs to authenticate the user. - The authentication provides data about user’s identity: a unique user ID or similar. - The user login and logout calls are managed by the app. - To access existing User object, use currentUser property: [block:code] { "codes": [ { "code": "let theUser: MOCAUser? = MOCA.currentInstance().currentUser", "language": "swift" }, { "code": "// Access authenticated user object\nMOCAUser * theUser = [[MOCA currentInstance] currentUser];\nif (theUser)\n{\n // ...\n}\n", "language": "objectivec" } ] } [/block] - To authenticate a new user, use *login:id* call: [block:callout] { "type": "warning", "body": "User will stay \"Logged in\" in MOCA SDK until you explicitly call the logout method", "title": "User will persist across restarts" } [/block] [block:code] { "codes": [ { "code": "let user = MOCA.currentInstance().login(\"[email protected]\")", "language": "swift" }, { "code": "MOCAUser * currentUser = [[MOCA currentInstance] login:@\"UNIQUE_USER_ID\"];\nif (!currentUser) {\n NSLog(@\"MOCA User login failed\");\n}\n", "language": "objectivec" } ] } [/block] - To logout a user, call: [block:code] { "codes": [ { "code": "user.logout()", "language": "swift" }, { "code": "[user logout];", "language": "objectivec" } ] } [/block] - The user object holds a collection of properties. Property-value pairs can be set and retrieved. - Each user object is persisted both locally and in the cloud. - It is recommended to perform as many sets as desired and then just invoke a single save operation to persist them to the MOCA cloud. [block:code] { "codes": [ { "code": "guard let user = MOCA.currentUser() else {\n print(\"MOCA User login failed\")\n return;\n}\nuser.setValue(\"male\", forProperty: \"gender\")\nuser.setValue(Int(1975), forProperty: \"birth_year\")\n// Asynchronously save the user object to the cloud.\nuser.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\n if error != nil {\n print(\"Save user failed: (%@)\", error ?? \"Error not available\")\n }\n })", "language": "swift" }, { "code": "MOCAUser * theUser = [[MOCA currentInstance] currentUser]; \nif (theUser) {\n [theUser setValue:@\"male\" forProperty:@\"gender\"];\n [theUser setValue:[NSNumber numberWithInt:1975] forProperty:@\"birth_year\"]; // Asynchronously save the user object to the cloud.\n [theUser saveWithBlock:^(MOCAUser *user, NSError *error)\n {\n if (error) NSLog(@\"Save user failed: %@\", error);\n }\n ];\n}", "language": "objectivec" } ] } [/block]
- The app **User object** manages information about current application user. - This object is **optional**, and it is used when the app needs to authenticate the user. - The authentication provides data about user’s identity: a unique user ID or similar. - The user login and logout calls are managed by the app. - To access existing User object, use currentUser property: [block:code] { "codes": [ { "code": "let theUser: MOCAUser? = MOCA.currentInstance().currentUser", "language": "swift" }, { "code": "// Access authenticated user object\nMOCAUser * theUser = [[MOCA currentInstance] currentUser];\nif (theUser)\n{\n // ...\n}\n", "language": "objectivec" } ] } [/block] - To authenticate a new user, use *login:id* call: [block:callout] { "type": "warning", "body": "User will stay \"Logged in\" in MOCA SDK until you explicitly call the logout method", "title": "User will persist across restarts" } [/block] [block:code] { "codes": [ { "code": "let user = MOCA.currentInstance().login(\"[email protected]\")", "language": "swift" }, { "code": "MOCAUser * currentUser = [[MOCA currentInstance] login:@\"UNIQUE_USER_ID\"];\nif (!currentUser) {\n NSLog(@\"MOCA User login failed\");\n}\n", "language": "objectivec" } ] } [/block] - To logout a user, call: [block:code] { "codes": [ { "code": "user.logout()", "language": "swift" }, { "code": "[user logout];", "language": "objectivec" } ] } [/block] - The user object holds a collection of properties. Property-value pairs can be set and retrieved. - Each user object is persisted both locally and in the cloud. - It is recommended to perform as many sets as desired and then just invoke a single save operation to persist them to the MOCA cloud. [block:code] { "codes": [ { "code": "guard let user = MOCA.currentUser() else {\n print(\"MOCA User login failed\")\n return;\n}\nuser.setValue(\"male\", forProperty: \"gender\")\nuser.setValue(Int(1975), forProperty: \"birth_year\")\n// Asynchronously save the user object to the cloud.\nuser.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\n if error != nil {\n print(\"Save user failed: (%@)\", error ?? \"Error not available\")\n }\n })", "language": "swift" }, { "code": "MOCAUser * theUser = [[MOCA currentInstance] currentUser]; \nif (theUser) {\n [theUser setValue:@\"male\" forProperty:@\"gender\"];\n [theUser setValue:[NSNumber numberWithInt:1975] forProperty:@\"birth_year\"]; // Asynchronously save the user object to the cloud.\n [theUser saveWithBlock:^(MOCAUser *user, NSError *error)\n {\n if (error) NSLog(@\"Save user failed: %@\", error);\n }\n ];\n}", "language": "objectivec" } ] } [/block]
{"_id":"5f998577fb81e800451c032d","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","params":[]},"next":{"description":"","pages":[]},"title":"Screen API","type":"basic","slug":"screen-api","excerpt":"","body":"MOCA SDK tracks automatically fragments/views of your App: this is great for tracking the screens viewed, where users dropped and how long they remained on each screen. In order to make the marketer's life easy we also offer a way to manually add a pretty name to each screen. You'll find an example below:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n * Sets the name of the current view controller. This information is used for \\\"Screen Analytics\\\"\\n * within MOCA.\\n *\\n * @param screenName the name of the current screen\\n * @param screenClass the class of the screen being tracked\\n */\\n+ (void)currentScreenName:(NSString *)screenName    \\n           forScreenClass:(UIViewController *)screenClass;\\n\\n//Call it using\\n[MOCA currentScreenName:@”My Magic Screen” forScreenClass:self];\\n\",\n      \"language\": \"objectivec\",\n      \"name\": null\n    }\n  ]\n}\n[/block]","updates":[],"order":9,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-09-01T13:01:22.538Z","user":"5a5c6e0737af2d001c9ed9ec","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Screen API


MOCA SDK tracks automatically fragments/views of your App: this is great for tracking the screens viewed, where users dropped and how long they remained on each screen. In order to make the marketer's life easy we also offer a way to manually add a pretty name to each screen. You'll find an example below: [block:code] { "codes": [ { "code": "/**\n * Sets the name of the current view controller. This information is used for \"Screen Analytics\"\n * within MOCA.\n *\n * @param screenName the name of the current screen\n * @param screenClass the class of the screen being tracked\n */\n+ (void)currentScreenName:(NSString *)screenName \n forScreenClass:(UIViewController *)screenClass;\n\n//Call it using\n[MOCA currentScreenName:@”My Magic Screen” forScreenClass:self];\n", "language": "objectivec", "name": null } ] } [/block]
MOCA SDK tracks automatically fragments/views of your App: this is great for tracking the screens viewed, where users dropped and how long they remained on each screen. In order to make the marketer's life easy we also offer a way to manually add a pretty name to each screen. You'll find an example below: [block:code] { "codes": [ { "code": "/**\n * Sets the name of the current view controller. This information is used for \"Screen Analytics\"\n * within MOCA.\n *\n * @param screenName the name of the current screen\n * @param screenClass the class of the screen being tracked\n */\n+ (void)currentScreenName:(NSString *)screenName \n forScreenClass:(UIViewController *)screenClass;\n\n//Call it using\n[MOCA currentScreenName:@”My Magic Screen” forScreenClass:self];\n", "language": "objectivec", "name": null } ] } [/block]
{"_id":"5f998577fb81e800451c0304","__v":0,"category":"5f998576fb81e800451c02f3","createdAt":"2015-07-17T13:31:59.715Z","next":{"pages":[],"description":""},"parentDoc":null,"type":"basic","api":{"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[]},"slug":"tags-1","title":"Tag API","updates":[],"version":"5f998577fb81e800451c032f","isReference":false,"link_external":false,"order":10,"sync_unique":"","user":"559a618bdbcfd20d00710b38","body":"# Introduction\n\n\n- One way to set user interests, is by using MOCA Tags\n- Tags are small items of information with well defined semantics. \n- Each tag is associated with a ***counter*** (integer). The counter is used to track how many times the user was tagged or to sum points associated with the tag. \n- Tags are defined in MOCA Console or by the app.\n- For example: `Restaurant` `Video Store`  `Parking` `Gym`\n- Tags can be attached to specific locations by using beacons or programmatically by API.\n- Tag counters are used to rank the tags.\n\n- MOCA provides the following methods to manipulate Tags.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@interface MOCAInstance\\n\\n#pragma mark Tags\\n\\n/**\\n * Add a tag to this instance and increment its value by 1.\\n */\\n-(void)addTag:(NSString*)tagName;\\n\\n/**\\n * Add a tag with a given value to this instance.\\n * @value - update expression with syntax [=|+|-] <double> value.\\n * For example \\\"+1\\\" increments the tag value by 1.\\n * For example \\\"-2\\\" decrements the tag value by 2. \\n * For example \\\"3\\\" or \\\"=3\\\" assign value of 3 to the tag's value.\\n */\\n-(void)addTag:(NSString*)tagName withValue:(NSString*)value;\\n\\n/**\\n * Checks if this instance contains a specific tag.\\n * @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\\n */\\n-(BOOL)containsTag:(NSString*)tagName;\\n\\n/**\\n * Retrieves a value of a specific tag associated with this instance.\\n * @return tag value or <code>nil</code> if the tag doest not exist.\\n */\\n-(NSNumber*)getTagValue:(NSString*)tagName;\\n\\n/**\\n * Retrieves top-k tags ranked by values.\\n */\\n-(NSArray*)getTopTags:(unsigned int)topK;\\n\\n/**\\n * Retrieves names of all tags associated with this instance.\\n */\\n-(NSArray*)allTags;\\n\\n#pragma mark\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"// MARK: Tags\\n/**\\n* Add a tag to this instance and increment its value by 1.\\n*/\\nfunc addTag(_ tagName: String)\\n\\n/**\\n* Add a tag with a given value to this instance.\\n* @value - update expression with syntax [=|+|-] <double> value.\\n* For example \\\"+1\\\" increments the tag value by 1.\\n* For example \\\"-2\\\" decrements the tag value by 2. \\n* For example \\\"3\\\" or \\\"=3\\\" assign value of 3 to the tag's value.\\n*/\\nfunc addTag(_ tagName: String, withValue value: String) \\n\\n/**\\n* Checks if this instance contains a specific tag.\\n* @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\\n*/\\nfunc containsTag(_ tagName: String) -> Bool\\n\\n/**\\n* Retrieves a value of a specific tag associated with this instance.\\n* @return tag value or <code>nil</code> if the tag doest not exist.\\n*/\\nfunc getTagValue(_ tagName: String) -> NSNumber\\n\\n/**\\n* Retrieves top-k tags ranked by values.\\n*/\\nfunc getTopTags(_ topK: UInt) -> [Any] \\n\\n/**\\n* Retrieves names of all tags associated with this instance.\\n*/\\nfunc allTags() -> [Any]\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]","excerpt":"","githubsync":"","hidden":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Tag API


# Introduction - One way to set user interests, is by using MOCA Tags - Tags are small items of information with well defined semantics. - Each tag is associated with a ***counter*** (integer). The counter is used to track how many times the user was tagged or to sum points associated with the tag. - Tags are defined in MOCA Console or by the app. - For example: `Restaurant` `Video Store` `Parking` `Gym` - Tags can be attached to specific locations by using beacons or programmatically by API. - Tag counters are used to rank the tags. - MOCA provides the following methods to manipulate Tags. [block:code] { "codes": [ { "code": "@interface MOCAInstance\n\n#pragma mark Tags\n\n/**\n * Add a tag to this instance and increment its value by 1.\n */\n-(void)addTag:(NSString*)tagName;\n\n/**\n * Add a tag with a given value to this instance.\n * @value - update expression with syntax [=|+|-] <double> value.\n * For example \"+1\" increments the tag value by 1.\n * For example \"-2\" decrements the tag value by 2. \n * For example \"3\" or \"=3\" assign value of 3 to the tag's value.\n */\n-(void)addTag:(NSString*)tagName withValue:(NSString*)value;\n\n/**\n * Checks if this instance contains a specific tag.\n * @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\n */\n-(BOOL)containsTag:(NSString*)tagName;\n\n/**\n * Retrieves a value of a specific tag associated with this instance.\n * @return tag value or <code>nil</code> if the tag doest not exist.\n */\n-(NSNumber*)getTagValue:(NSString*)tagName;\n\n/**\n * Retrieves top-k tags ranked by values.\n */\n-(NSArray*)getTopTags:(unsigned int)topK;\n\n/**\n * Retrieves names of all tags associated with this instance.\n */\n-(NSArray*)allTags;\n\n#pragma mark\n", "language": "objectivec" }, { "code": "// MARK: Tags\n/**\n* Add a tag to this instance and increment its value by 1.\n*/\nfunc addTag(_ tagName: String)\n\n/**\n* Add a tag with a given value to this instance.\n* @value - update expression with syntax [=|+|-] <double> value.\n* For example \"+1\" increments the tag value by 1.\n* For example \"-2\" decrements the tag value by 2. \n* For example \"3\" or \"=3\" assign value of 3 to the tag's value.\n*/\nfunc addTag(_ tagName: String, withValue value: String) \n\n/**\n* Checks if this instance contains a specific tag.\n* @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\n*/\nfunc containsTag(_ tagName: String) -> Bool\n\n/**\n* Retrieves a value of a specific tag associated with this instance.\n* @return tag value or <code>nil</code> if the tag doest not exist.\n*/\nfunc getTagValue(_ tagName: String) -> NSNumber\n\n/**\n* Retrieves top-k tags ranked by values.\n*/\nfunc getTopTags(_ topK: UInt) -> [Any] \n\n/**\n* Retrieves names of all tags associated with this instance.\n*/\nfunc allTags() -> [Any]", "language": "swift" } ] } [/block]
# Introduction - One way to set user interests, is by using MOCA Tags - Tags are small items of information with well defined semantics. - Each tag is associated with a ***counter*** (integer). The counter is used to track how many times the user was tagged or to sum points associated with the tag. - Tags are defined in MOCA Console or by the app. - For example: `Restaurant` `Video Store` `Parking` `Gym` - Tags can be attached to specific locations by using beacons or programmatically by API. - Tag counters are used to rank the tags. - MOCA provides the following methods to manipulate Tags. [block:code] { "codes": [ { "code": "@interface MOCAInstance\n\n#pragma mark Tags\n\n/**\n * Add a tag to this instance and increment its value by 1.\n */\n-(void)addTag:(NSString*)tagName;\n\n/**\n * Add a tag with a given value to this instance.\n * @value - update expression with syntax [=|+|-] <double> value.\n * For example \"+1\" increments the tag value by 1.\n * For example \"-2\" decrements the tag value by 2. \n * For example \"3\" or \"=3\" assign value of 3 to the tag's value.\n */\n-(void)addTag:(NSString*)tagName withValue:(NSString*)value;\n\n/**\n * Checks if this instance contains a specific tag.\n * @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\n */\n-(BOOL)containsTag:(NSString*)tagName;\n\n/**\n * Retrieves a value of a specific tag associated with this instance.\n * @return tag value or <code>nil</code> if the tag doest not exist.\n */\n-(NSNumber*)getTagValue:(NSString*)tagName;\n\n/**\n * Retrieves top-k tags ranked by values.\n */\n-(NSArray*)getTopTags:(unsigned int)topK;\n\n/**\n * Retrieves names of all tags associated with this instance.\n */\n-(NSArray*)allTags;\n\n#pragma mark\n", "language": "objectivec" }, { "code": "// MARK: Tags\n/**\n* Add a tag to this instance and increment its value by 1.\n*/\nfunc addTag(_ tagName: String)\n\n/**\n* Add a tag with a given value to this instance.\n* @value - update expression with syntax [=|+|-] <double> value.\n* For example \"+1\" increments the tag value by 1.\n* For example \"-2\" decrements the tag value by 2. \n* For example \"3\" or \"=3\" assign value of 3 to the tag's value.\n*/\nfunc addTag(_ tagName: String, withValue value: String) \n\n/**\n* Checks if this instance contains a specific tag.\n* @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\n*/\nfunc containsTag(_ tagName: String) -> Bool\n\n/**\n* Retrieves a value of a specific tag associated with this instance.\n* @return tag value or <code>nil</code> if the tag doest not exist.\n*/\nfunc getTagValue(_ tagName: String) -> NSNumber\n\n/**\n* Retrieves top-k tags ranked by values.\n*/\nfunc getTopTags(_ topK: UInt) -> [Any] \n\n/**\n* Retrieves names of all tags associated with this instance.\n*/\nfunc allTags() -> [Any]", "language": "swift" } ] } [/block]
{"_id":"5f9af0e34245870018911c94","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Location Events Listener","type":"basic","slug":"location-events-listener","excerpt":"","body":"Your application can listen to location `enter` or `exit` events. \nBefore deep diving into the available methods, lets briefly see what kind of location objects does MOCA define:\n[block:api-header]\n{\n  \"title\": \"Location related classes\"\n}\n[/block]\n`MOCABeacon`: A bluetooth beacon.\n`MOCAZone`: A Group of `MOCABeacon`.\n`MOCAPlace`: A region defined by a geofence. It could contain multiple `MOCAZone`\n`MOCARegionGroup`: Flexible class that can contain multiple `MOCABeacon`, `MOCAZone ` or `MOCAPlace `.\n\nAll classes above inherit from `MOCARegion`\n[block:api-header]\n{\n  \"title\": \"Available methods\"\n}\n[/block]\nLocation event listening is segregated in several interfaces so you can pick what works best for your use case.\n\nListening to _all_ region type events: \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@protocol RegionEventsObserver <MOCAObserverId>\\[email protected]\\n- (void)didEnterRegion:(MOCARegion *)region;\\n- (void)didExitRegion:(MOCARegion *)region;\\[email protected]\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\nIf you want to listen only a specific type of regions. Implement the appropriate protocol.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@protocol RegionGroupEventsObserver <RegionEventsObserver>\\n- (void)didEnterRegionGroup:(MOCARegionGroup *)regionGroup;\\n- (void)didExitRegionGroup:(MOCARegionGroup *)regionGroup;\\[email protected]\\n\\[email protected] PlaceEventsObserver <RegionEventsObserver>\\n- (void)didEnterPlace:(MOCAPlace *)place;\\n- (void)didExitPlace:(MOCAPlace *)place;\\[email protected]\\n\\[email protected] ZoneEventsObserver <RegionEventsObserver>\\n- (void)didEnterZone:(MOCAZone *)zone;\\n- (void)didExitZone:(MOCAZone *)zone;\\[email protected]\\n\\[email protected] BeaconEventsObserver <RegionEventsObserver>\\n- (void)didEnterBeacon:(MOCABeacon *)beacon;\\n- (void)didExitBeacon:(MOCABeacon *)beacon;\\n- (void)\\tdidRangeBeacon:(MOCABeacon *)beacon \\n\\t\\t\\t\\t\\t withProximity:(CLProximity)proximity;\\[email protected]\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","updates":[],"order":15,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-10-29T16:42:11.291Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Location Events Listener


Your application can listen to location `enter` or `exit` events. Before deep diving into the available methods, lets briefly see what kind of location objects does MOCA define: [block:api-header] { "title": "Location related classes" } [/block] `MOCABeacon`: A bluetooth beacon. `MOCAZone`: A Group of `MOCABeacon`. `MOCAPlace`: A region defined by a geofence. It could contain multiple `MOCAZone` `MOCARegionGroup`: Flexible class that can contain multiple `MOCABeacon`, `MOCAZone ` or `MOCAPlace `. All classes above inherit from `MOCARegion` [block:api-header] { "title": "Available methods" } [/block] Location event listening is segregated in several interfaces so you can pick what works best for your use case. Listening to _all_ region type events: [block:code] { "codes": [ { "code": "@protocol RegionEventsObserver <MOCAObserverId>\[email protected]\n- (void)didEnterRegion:(MOCARegion *)region;\n- (void)didExitRegion:(MOCARegion *)region;\[email protected]", "language": "objectivec" } ] } [/block] If you want to listen only a specific type of regions. Implement the appropriate protocol. [block:code] { "codes": [ { "code": "@protocol RegionGroupEventsObserver <RegionEventsObserver>\n- (void)didEnterRegionGroup:(MOCARegionGroup *)regionGroup;\n- (void)didExitRegionGroup:(MOCARegionGroup *)regionGroup;\[email protected]\n\[email protected] PlaceEventsObserver <RegionEventsObserver>\n- (void)didEnterPlace:(MOCAPlace *)place;\n- (void)didExitPlace:(MOCAPlace *)place;\[email protected]\n\[email protected] ZoneEventsObserver <RegionEventsObserver>\n- (void)didEnterZone:(MOCAZone *)zone;\n- (void)didExitZone:(MOCAZone *)zone;\[email protected]\n\[email protected] BeaconEventsObserver <RegionEventsObserver>\n- (void)didEnterBeacon:(MOCABeacon *)beacon;\n- (void)didExitBeacon:(MOCABeacon *)beacon;\n- (void)\tdidRangeBeacon:(MOCABeacon *)beacon \n\t\t\t\t\t withProximity:(CLProximity)proximity;\[email protected]", "language": "objectivec" } ] } [/block]
Your application can listen to location `enter` or `exit` events. Before deep diving into the available methods, lets briefly see what kind of location objects does MOCA define: [block:api-header] { "title": "Location related classes" } [/block] `MOCABeacon`: A bluetooth beacon. `MOCAZone`: A Group of `MOCABeacon`. `MOCAPlace`: A region defined by a geofence. It could contain multiple `MOCAZone` `MOCARegionGroup`: Flexible class that can contain multiple `MOCABeacon`, `MOCAZone ` or `MOCAPlace `. All classes above inherit from `MOCARegion` [block:api-header] { "title": "Available methods" } [/block] Location event listening is segregated in several interfaces so you can pick what works best for your use case. Listening to _all_ region type events: [block:code] { "codes": [ { "code": "@protocol RegionEventsObserver <MOCAObserverId>\[email protected]\n- (void)didEnterRegion:(MOCARegion *)region;\n- (void)didExitRegion:(MOCARegion *)region;\[email protected]", "language": "objectivec" } ] } [/block] If you want to listen only a specific type of regions. Implement the appropriate protocol. [block:code] { "codes": [ { "code": "@protocol RegionGroupEventsObserver <RegionEventsObserver>\n- (void)didEnterRegionGroup:(MOCARegionGroup *)regionGroup;\n- (void)didExitRegionGroup:(MOCARegionGroup *)regionGroup;\[email protected]\n\[email protected] PlaceEventsObserver <RegionEventsObserver>\n- (void)didEnterPlace:(MOCAPlace *)place;\n- (void)didExitPlace:(MOCAPlace *)place;\[email protected]\n\[email protected] ZoneEventsObserver <RegionEventsObserver>\n- (void)didEnterZone:(MOCAZone *)zone;\n- (void)didExitZone:(MOCAZone *)zone;\[email protected]\n\[email protected] BeaconEventsObserver <RegionEventsObserver>\n- (void)didEnterBeacon:(MOCABeacon *)beacon;\n- (void)didExitBeacon:(MOCABeacon *)beacon;\n- (void)\tdidRangeBeacon:(MOCABeacon *)beacon \n\t\t\t\t\t withProximity:(CLProximity)proximity;\[email protected]", "language": "objectivec" } ] } [/block]
{"_id":"5f998577fb81e800451c02fc","__v":0,"body":"- Geofencing:\n    - \"Exit\" event, can take up to 2 minutes to happen. This is a iOS CoreLocation limitation to limit the application power consumption.\n- Beacon detection:\n    - Bluetooth Beacon detection cannot be tested in the simulator, you will need a real device (iPhone 4s or newer).","createdAt":"2015-07-17T14:31:06.333Z","hidden":false,"order":16,"type":"basic","api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","isReference":false,"next":{"description":"","pages":[]},"slug":"known-issues","title":"Known issues and limitations","version":"5f998577fb81e800451c032f","category":"5f998576fb81e800451c02f3","githubsync":"","parentDoc":null,"project":"559a61d2dbcfd20d00710b39","user":"559a618bdbcfd20d00710b38","link_external":false,"link_url":"","sync_unique":"","updates":[],"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Known issues and limitations


- Geofencing: - "Exit" event, can take up to 2 minutes to happen. This is a iOS CoreLocation limitation to limit the application power consumption. - Beacon detection: - Bluetooth Beacon detection cannot be tested in the simulator, you will need a real device (iPhone 4s or newer).
- Geofencing: - "Exit" event, can take up to 2 minutes to happen. This is a iOS CoreLocation limitation to limit the application power consumption. - Beacon detection: - Bluetooth Beacon detection cannot be tested in the simulator, you will need a real device (iPhone 4s or newer).
{"_id":"5fa19560b7b3610032c8dcba","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Custom event tracking","type":"basic","slug":"custom-event-tracking","excerpt":"","body":"This sample code shows how to track a generic, custom event within the app.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Track custom events\\n\\nMOCAEvent.track(\\\"verb\\\",forItem:\\\"item\\\",belongingTo:\\\"category\\\", ...)\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"# Track custom events\\n\\n[MOCAEvent track:@”verb\\\" forItem:@”item\\\" belongingTo:@”category” . . . ];\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","updates":[],"order":17,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-11-03T17:37:36.398Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Custom event tracking


This sample code shows how to track a generic, custom event within the app. [block:code] { "codes": [ { "code": "// Track custom events\n\nMOCAEvent.track(\"verb\",forItem:\"item\",belongingTo:\"category\", ...)", "language": "swift" }, { "code": "# Track custom events\n\n[MOCAEvent track:@”verb\" forItem:@”item\" belongingTo:@”category” . . . ];\n", "language": "objectivec" } ] } [/block]
This sample code shows how to track a generic, custom event within the app. [block:code] { "codes": [ { "code": "// Track custom events\n\nMOCAEvent.track(\"verb\",forItem:\"item\",belongingTo:\"category\", ...)", "language": "swift" }, { "code": "# Track custom events\n\n[MOCAEvent track:@”verb\" forItem:@”item\" belongingTo:@”category” . . . ];\n", "language": "objectivec" } ] } [/block]
{"_id":"5fa196ed8ed8d70148218d2e","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Location and Notification permissions","type":"basic","slug":"location-and-notification-permissions","excerpt":"","body":"By default MOCA SDK will request both notifications and location (\"Always\") permission the first time it gets executed. \n\nIt is recommended that your application requests these permissions instead. In order to do so:\n\n1 - Disable MOCA SDK permissions request:\n\nGo to your `MOCAConfig.plist` file and add / modify these keys:\n\nKey\n`REQUEST_NOTIFICATIONS_PERMISSION`\nType\n`Boolean`\nValue\n`0`\n:warning:  important: This key is supported in the MOCA iOS SDK version 3.2.0+\n\nDisable location permissions request:\n\nKey\n`LOCATION_PERMISSION_REQUEST_MODE`\nType\n`String`\nValue\n`Disabled`\n\nOnce the user has granted permission. Enable location dependent services:\n\n```\n[MOCA setProximityEnabled:YES]\n[MOCA setGeoTrackingEnabled:YES]\n```\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Location permission\",\n  \"body\": \"Location permission \\\"Always\\\" is required in order to be able to detect geofences and bluetooth beacons.\"\n}\n[/block]","updates":[],"order":18,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-11-03T17:44:13.872Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Location and Notification permissions


By default MOCA SDK will request both notifications and location ("Always") permission the first time it gets executed. It is recommended that your application requests these permissions instead. In order to do so: 1 - Disable MOCA SDK permissions request: Go to your `MOCAConfig.plist` file and add / modify these keys: Key `REQUEST_NOTIFICATIONS_PERMISSION` Type `Boolean` Value `0` :warning: important: This key is supported in the MOCA iOS SDK version 3.2.0+ Disable location permissions request: Key `LOCATION_PERMISSION_REQUEST_MODE` Type `String` Value `Disabled` Once the user has granted permission. Enable location dependent services: ``` [MOCA setProximityEnabled:YES] [MOCA setGeoTrackingEnabled:YES] ``` [block:callout] { "type": "warning", "title": "Location permission", "body": "Location permission \"Always\" is required in order to be able to detect geofences and bluetooth beacons." } [/block]
By default MOCA SDK will request both notifications and location ("Always") permission the first time it gets executed. It is recommended that your application requests these permissions instead. In order to do so: 1 - Disable MOCA SDK permissions request: Go to your `MOCAConfig.plist` file and add / modify these keys: Key `REQUEST_NOTIFICATIONS_PERMISSION` Type `Boolean` Value `0` :warning: important: This key is supported in the MOCA iOS SDK version 3.2.0+ Disable location permissions request: Key `LOCATION_PERMISSION_REQUEST_MODE` Type `String` Value `Disabled` Once the user has granted permission. Enable location dependent services: ``` [MOCA setProximityEnabled:YES] [MOCA setGeoTrackingEnabled:YES] ``` [block:callout] { "type": "warning", "title": "Location permission", "body": "Location permission \"Always\" is required in order to be able to detect geofences and bluetooth beacons." } [/block]
{"_id":"5fa19787fed297001e582873","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Custom experiences handling","type":"basic","slug":"custom-experiences-handling","excerpt":"","body":"Optionally, you can handle \"custom\" MOCA Experiences yourself. The SDK will evaluate the campaign and experience settings, and let you know when the events happened so you can react accordingly.\n\nRegister your handler by calling \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.customActionHandler = self; \",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\nWhere `self` implements the `MOCACustomActionHandler` protocol.","updates":[],"order":19,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-11-03T17:46:47.914Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f3","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Custom experiences handling


Optionally, you can handle "custom" MOCA Experiences yourself. The SDK will evaluate the campaign and experience settings, and let you know when the events happened so you can react accordingly. Register your handler by calling [block:code] { "codes": [ { "code": "MOCA.customActionHandler = self; ", "language": "swift" } ] } [/block] Where `self` implements the `MOCACustomActionHandler` protocol.
Optionally, you can handle "custom" MOCA Experiences yourself. The SDK will evaluate the campaign and experience settings, and let you know when the events happened so you can react accordingly. Register your handler by calling [block:code] { "codes": [ { "code": "MOCA.customActionHandler = self; ", "language": "swift" } ] } [/block] Where `self` implements the `MOCACustomActionHandler` protocol.
{"_id":"5fe0b3e0d58e19004a267a63","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Migration from 2.x to 3.x","type":"basic","slug":"migration-from-2x-to-3x","excerpt":"","body":"[block:api-header]\n{\n  \"title\": \"Dependencies\"\n}\n[/block]\n- MOCA SDK 3.0.0 now uses AndroidX. If your application does not use AndroidX, you won't be able to use MOCA SDK 3.0+\n[block:api-header]\n{\n  \"title\": \"Language changes\"\n}\n[/block]\nMOCA SDK now uses Java 8 through the Android Gradle Plugin 4.0.0. (It works even in API level versions before 24)\n\nPlease check the [Installation](https://developer.mocaplatform.com/v3-sdk/docs/moca-android-sdk-installation#java-8-support) in order to see how to support it in your application.\n[block:api-header]\n{\n  \"title\": \"Configuration changes\"\n}\n[/block]\nConfiguration through the `AndroidManifest.xml` is now deprecated and will be removed soon. If you configure MOCA SDK through the `AndroidManifest.xml`, please migrate it to the easier to read and maintain `MOCA.properties` option. More information in the  [Configuration doc](doc:moca-android-sdk-configuration)\n\n[block:api-header]\n{\n  \"title\": \"API Changes\"\n}\n[/block]\n**Removed methods**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"public static void registerGeofenceListener(GeofencingService.Listener listener) \\npublic static void deregisterGeofenceListener(GeofencingService.Listener listenerToRemove);\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nUse the new [Location Events Listener](doc:location-events-listener-android)\n\n**Removed method**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    public static boolean performFetchWithCallback(final MOCACallback<ProximityData> callback, final boolean forceSync);\\n\\n    public static boolean performFetchWithCallback(final MOCACallback<ProximityData> callback);\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nYou can force a fetch by invoking:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.getDataStore().fetch(true);\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nPlease note that this method is not necessary for any integration as the data fetching is automatically managed by the SDK. This method is exposed primarily for our companion app MOCApp.\n\n**Proximity Events Listener interface**\n\n This interface has been replaced by the new [Location Events Listener Android](doc:location-events-listener-android) Events Listener interface. \n\n**Action Listener Interface**\n\nThe interface has been removed. In order to integrate with custom actions, please refer to the document: [Custom experiences handling](doc:custom-experiences-handling-android) experiences handling]","updates":[],"order":0,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T14:40:32.108Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Migration from 2.x to 3.x


[block:api-header] { "title": "Dependencies" } [/block] - MOCA SDK 3.0.0 now uses AndroidX. If your application does not use AndroidX, you won't be able to use MOCA SDK 3.0+ [block:api-header] { "title": "Language changes" } [/block] MOCA SDK now uses Java 8 through the Android Gradle Plugin 4.0.0. (It works even in API level versions before 24) Please check the [Installation](https://developer.mocaplatform.com/v3-sdk/docs/moca-android-sdk-installation#java-8-support) in order to see how to support it in your application. [block:api-header] { "title": "Configuration changes" } [/block] Configuration through the `AndroidManifest.xml` is now deprecated and will be removed soon. If you configure MOCA SDK through the `AndroidManifest.xml`, please migrate it to the easier to read and maintain `MOCA.properties` option. More information in the [Configuration doc](doc:moca-android-sdk-configuration) [block:api-header] { "title": "API Changes" } [/block] **Removed methods** [block:code] { "codes": [ { "code": "public static void registerGeofenceListener(GeofencingService.Listener listener) \npublic static void deregisterGeofenceListener(GeofencingService.Listener listenerToRemove);", "language": "java" } ] } [/block] Use the new [Location Events Listener](doc:location-events-listener-android) **Removed method** [block:code] { "codes": [ { "code": " public static boolean performFetchWithCallback(final MOCACallback<ProximityData> callback, final boolean forceSync);\n\n public static boolean performFetchWithCallback(final MOCACallback<ProximityData> callback);\n", "language": "java" } ] } [/block] You can force a fetch by invoking: [block:code] { "codes": [ { "code": "MOCA.getDataStore().fetch(true);", "language": "java" } ] } [/block] Please note that this method is not necessary for any integration as the data fetching is automatically managed by the SDK. This method is exposed primarily for our companion app MOCApp. **Proximity Events Listener interface** This interface has been replaced by the new [Location Events Listener Android](doc:location-events-listener-android) Events Listener interface. **Action Listener Interface** The interface has been removed. In order to integrate with custom actions, please refer to the document: [Custom experiences handling](doc:custom-experiences-handling-android) experiences handling]
[block:api-header] { "title": "Dependencies" } [/block] - MOCA SDK 3.0.0 now uses AndroidX. If your application does not use AndroidX, you won't be able to use MOCA SDK 3.0+ [block:api-header] { "title": "Language changes" } [/block] MOCA SDK now uses Java 8 through the Android Gradle Plugin 4.0.0. (It works even in API level versions before 24) Please check the [Installation](https://developer.mocaplatform.com/v3-sdk/docs/moca-android-sdk-installation#java-8-support) in order to see how to support it in your application. [block:api-header] { "title": "Configuration changes" } [/block] Configuration through the `AndroidManifest.xml` is now deprecated and will be removed soon. If you configure MOCA SDK through the `AndroidManifest.xml`, please migrate it to the easier to read and maintain `MOCA.properties` option. More information in the [Configuration doc](doc:moca-android-sdk-configuration) [block:api-header] { "title": "API Changes" } [/block] **Removed methods** [block:code] { "codes": [ { "code": "public static void registerGeofenceListener(GeofencingService.Listener listener) \npublic static void deregisterGeofenceListener(GeofencingService.Listener listenerToRemove);", "language": "java" } ] } [/block] Use the new [Location Events Listener](doc:location-events-listener-android) **Removed method** [block:code] { "codes": [ { "code": " public static boolean performFetchWithCallback(final MOCACallback<ProximityData> callback, final boolean forceSync);\n\n public static boolean performFetchWithCallback(final MOCACallback<ProximityData> callback);\n", "language": "java" } ] } [/block] You can force a fetch by invoking: [block:code] { "codes": [ { "code": "MOCA.getDataStore().fetch(true);", "language": "java" } ] } [/block] Please note that this method is not necessary for any integration as the data fetching is automatically managed by the SDK. This method is exposed primarily for our companion app MOCApp. **Proximity Events Listener interface** This interface has been replaced by the new [Location Events Listener Android](doc:location-events-listener-android) Events Listener interface. **Action Listener Interface** The interface has been removed. In order to integrate with custom actions, please refer to the document: [Custom experiences handling](doc:custom-experiences-handling-android) experiences handling]
{"_id":"5f998577fb81e800451c0321","link_external":false,"next":{"pages":[],"description":""},"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","slug":"moca-android-sdk-installation","updates":[],"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Requirements\"\n}\n[/block]\n- Android Studio IDE. \n- An existing application\n\nMOCA SDK works supports Android API 19 (4.4 KitKat) and greater.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Gradle\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"REMINDER\",\n  \"body\": \"The `build.gradle` has to be the one in your app folder, not the main one in your project\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"repositories {\\n    maven { url 'https://dl.bintray.com/mocaplatform/maven' }\\n}\\n\\nandroid {\\n    . . .\\n}\\n\\ndependencies {\\n    . . .\\n    implementation 'com.mocaplatform:moca-android-sdk:3.3.0'\\n}\",\n      \"language\": \"groovy\",\n      \"name\": \"build.gradle\"\n    }\n  ]\n}\n[/block]\nLatest version:\n <a href='https://bintray.com/mocaplatform/maven/moca-android/_latestVersion'><img src='https://api.bintray.com/packages/mocaplatform/maven/moca-android/images/download.svg'></a>\n\n\nNext: [Configuration](doc:moca-android-sdk-configuration)\n[block:api-header]\n{\n  \"title\": \"Dependencies and additional requirements\"\n}\n[/block]\nMOCA SDK dependencies will be automatically installed when importing the library through Android Studio. Important notes about MOCA SDK for Android dependencies:\n\n- This project uses [AndroidX](https://developer.android.com/jetpack/androidx). If your project has not migrated yet to AndroidX, we encourage you to do so, otherwise you won't be able to use this SDK not many other modern Android libraries.\n- This project uses Java 8 via _desugaring_. Please be sure your project has updated the [Android Gradle plugin](https://developer.android.com/studio/releases/gradle-plugin) to the version 4.0.0 or greater.\n\n[block:api-header]\n{\n  \"title\": \"Java 8 support\"\n}\n[/block]\nIn addition to the Android Gradle plugin version. Please include the following lines in your `build.gralde` file (app level)\n\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"android {\\n    ...\\n    compileOptions {\\n        coreLibraryDesugaringEnabled true\\n        sourceCompatibility JavaVersion.VERSION_1_8\\n        targetCompatibility JavaVersion.VERSION_1_8\\n    }\\n}\\ndependencies {\\n    ...\\n}\",\n      \"language\": \"groovy\"\n    }\n  ]\n}\n[/block]\nIf your application supports Android API Level below 20. Make sure multidex is also enabled.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"android {\\n    ...\\n    defaultConfig {\\n        multiDexEnabled true\\n    }\\n}\",\n      \"language\": \"groovy\"\n    }\n  ]\n}\n[/block]","excerpt":"","user":"55a575ebaaf9cf1900114d73","createdAt":"2015-07-14T22:48:39.299Z","githubsync":"","isReference":false,"link_url":"","sync_unique":"","title":"Installation","version":"5f998577fb81e800451c032f","api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required"},"category":"5f998576fb81e800451c02f5","hidden":false,"order":1,"type":"basic","__v":0,"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Installation


[block:api-header] { "type": "basic", "title": "Requirements" } [/block] - Android Studio IDE. - An existing application MOCA SDK works supports Android API 19 (4.4 KitKat) and greater. [block:api-header] { "type": "basic", "title": "Gradle" } [/block] [block:callout] { "type": "warning", "title": "REMINDER", "body": "The `build.gradle` has to be the one in your app folder, not the main one in your project" } [/block] [block:code] { "codes": [ { "code": "repositories {\n maven { url 'https://dl.bintray.com/mocaplatform/maven' }\n}\n\nandroid {\n . . .\n}\n\ndependencies {\n . . .\n implementation 'com.mocaplatform:moca-android-sdk:3.3.0'\n}", "language": "groovy", "name": "build.gradle" } ] } [/block] Latest version: <a href='https://bintray.com/mocaplatform/maven/moca-android/_latestVersion'><img src='https://api.bintray.com/packages/mocaplatform/maven/moca-android/images/download.svg'></a> Next: [Configuration](doc:moca-android-sdk-configuration) [block:api-header] { "title": "Dependencies and additional requirements" } [/block] MOCA SDK dependencies will be automatically installed when importing the library through Android Studio. Important notes about MOCA SDK for Android dependencies: - This project uses [AndroidX](https://developer.android.com/jetpack/androidx). If your project has not migrated yet to AndroidX, we encourage you to do so, otherwise you won't be able to use this SDK not many other modern Android libraries. - This project uses Java 8 via _desugaring_. Please be sure your project has updated the [Android Gradle plugin](https://developer.android.com/studio/releases/gradle-plugin) to the version 4.0.0 or greater. [block:api-header] { "title": "Java 8 support" } [/block] In addition to the Android Gradle plugin version. Please include the following lines in your `build.gralde` file (app level) [block:code] { "codes": [ { "code": "android {\n ...\n compileOptions {\n coreLibraryDesugaringEnabled true\n sourceCompatibility JavaVersion.VERSION_1_8\n targetCompatibility JavaVersion.VERSION_1_8\n }\n}\ndependencies {\n ...\n}", "language": "groovy" } ] } [/block] If your application supports Android API Level below 20. Make sure multidex is also enabled. [block:code] { "codes": [ { "code": "android {\n ...\n defaultConfig {\n multiDexEnabled true\n }\n}", "language": "groovy" } ] } [/block]
[block:api-header] { "type": "basic", "title": "Requirements" } [/block] - Android Studio IDE. - An existing application MOCA SDK works supports Android API 19 (4.4 KitKat) and greater. [block:api-header] { "type": "basic", "title": "Gradle" } [/block] [block:callout] { "type": "warning", "title": "REMINDER", "body": "The `build.gradle` has to be the one in your app folder, not the main one in your project" } [/block] [block:code] { "codes": [ { "code": "repositories {\n maven { url 'https://dl.bintray.com/mocaplatform/maven' }\n}\n\nandroid {\n . . .\n}\n\ndependencies {\n . . .\n implementation 'com.mocaplatform:moca-android-sdk:3.3.0'\n}", "language": "groovy", "name": "build.gradle" } ] } [/block] Latest version: <a href='https://bintray.com/mocaplatform/maven/moca-android/_latestVersion'><img src='https://api.bintray.com/packages/mocaplatform/maven/moca-android/images/download.svg'></a> Next: [Configuration](doc:moca-android-sdk-configuration) [block:api-header] { "title": "Dependencies and additional requirements" } [/block] MOCA SDK dependencies will be automatically installed when importing the library through Android Studio. Important notes about MOCA SDK for Android dependencies: - This project uses [AndroidX](https://developer.android.com/jetpack/androidx). If your project has not migrated yet to AndroidX, we encourage you to do so, otherwise you won't be able to use this SDK not many other modern Android libraries. - This project uses Java 8 via _desugaring_. Please be sure your project has updated the [Android Gradle plugin](https://developer.android.com/studio/releases/gradle-plugin) to the version 4.0.0 or greater. [block:api-header] { "title": "Java 8 support" } [/block] In addition to the Android Gradle plugin version. Please include the following lines in your `build.gralde` file (app level) [block:code] { "codes": [ { "code": "android {\n ...\n compileOptions {\n coreLibraryDesugaringEnabled true\n sourceCompatibility JavaVersion.VERSION_1_8\n targetCompatibility JavaVersion.VERSION_1_8\n }\n}\ndependencies {\n ...\n}", "language": "groovy" } ] } [/block] If your application supports Android API Level below 20. Make sure multidex is also enabled. [block:code] { "codes": [ { "code": "android {\n ...\n defaultConfig {\n multiDexEnabled true\n }\n}", "language": "groovy" } ] } [/block]
{"_id":"5f998577fb81e800451c0322","link_external":false,"next":{"description":"","pages":[]},"order":2,"project":"559a61d2dbcfd20d00710b39","hidden":false,"excerpt":"","version":"5f998577fb81e800451c032f","__v":0,"link_url":"","slug":"moca-android-sdk-configuration","category":"5f998576fb81e800451c02f5","body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Grab your AppKey and AppSecret\"\n}\n[/block]\n1 - Go to [https://console.mocaplatform.com](https://console.mocaplatform.com) and sign into your MOCA account.  \n2 - Select Apps item at left sidebar, and then click + New App in the content panel. Fill in the form and complete the app creation.  \n3 - Open the newly created app and navigate to Settings item. Select API keys tab.\n4 - Get `App Key` and `App Secret`. \n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/jvi2iXdScWdM4W428eiX_consolekeys.png\",\n        \"consolekeys.png\",\n        \"704\",\n        \"458\",\n        \"#b02428\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\nYou can configure the MOCA SDK from the `AndroidManifest.xml` file, or alternatively from a `MOCA.properties` file\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"MOCA.properties file\"\n}\n[/block]\nStarting from MOCA Android SDK 1.9.0, you can configure the SDK using a `MOCA.properties` file. \n\n1 - Create an `assets` folder, just inside your App's main folder.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/1k7sOod6QFGfMreUtwCl_assets-folder.png\",\n        \"assets-folder.png\",\n        \"700\",\n        \"598\",\n        \"#5a8fce\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\nYou should be able to see a new folder in your project.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/9IgnTA5oSDqOMtqk5Xw0_assets.png\",\n        \"assets.png\",\n        \"272\",\n        \"272\",\n        \"#4d87d1\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n2 - Create a file called `MOCA.properties` by right clicking the `assets` folder and selecting New > File.\n\n3 - Configure the SDK with the necessary keys. Please bear in mind that ***the only mandatory keys are AppKey, and AppSecret***. \nThe ***gcmSender*** is mandatory only if you want to use MOCA Remote Push Notifications service.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Get your GCM Sender from Google\",\n  \"body\": \"Check [this guide](./gcm-fcm-cloud-messaging-setup) in order to get your Cloud Messaging Sender Id.\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"\",\n  \"body\": \"Don't forget to paste the AppKey and AppSecret with the ones corresponding to your App. Otherwise the SDK won't be able to connect to MOCA Cloud.\"\n}\n[/block]\nContents of the `MOCA.properties` file:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#MOCA App key and app secret. You can get this keys from the MOCA Console.\\nappKey = YOUR-MOCA-APP-KEY\\nappSecret = YOUR-MOCA-APP-SECRET\\n\\n#MOCA SDK Log level. Possible values [Off, Error,  Warning, Info, Debug, Verbose]\\nlogLevel = Debug\\n\\n# MOCA Remote Push Notifications\\n# disable it if you have your own/ other remote push implementation\\nremotePushNotificationsService = true\\n\\n# MOCA Proximity Service includes beacon and geofence detection\\nproximityService = true\\n\\n# MOCA GeoTracking Service generates geo points periodically for analytics\\ngeoTrackingService = true\\n\\n# MOCA Event Tracking Service. If enabled, activates event tracking (Sessions, custom events etc.)\\neventTrackingService = true\\n\\n# MOCA driver. This is required for Bluetooth Beacon detection. Set it to false if a custom\\n# beacon driver is being used\\nmocaDriver = true\\n\\n# Background location. Allows geoTracking in background\\nbackgroundLocation = true\\n\\n# GCM Sender ID. Only needed if you are using MOCA Remote Push Notifications.\\ngcmSender = YOUR-GCM-SENDER-ID\\n\\n# Beacon detection engine profile [LowLatency, Balanced, BatterySaver, Custom]\\n# LowLatency = Notifications will be delivered almost instantly in foreground and background.\\n# but will have an important impact on the user's device battery.\\n# Balanced = Notifications are delivered almost instantly in foreground. In background it can\\n# take up to one minute. In Android Lollipop, Marshmallow, and N there are operating system\\n# optimizations that reduce the notification delay (Default setting).\\n# BatterySaver = Detections in foreground can take up to one minute, and in background up to\\n#5 minutes. this is the recommended setting for analytics-only usages.\\n# \\nbeaconProfile = Balanced\\n\\n# If beaconProfile is \\\"Custom\\\", the following parameters are mandatory\\n# foregroundTimeBetweenScans: Time between each scan in milliseconds, close scans means faster response, but\\n#  more battery consumption.\\n# foregroundScanDuration: Time while device will be listening bluetooth signals in milliseconds.\\n#  We recommend at least 1100 ms, so if your beacon broadcasts a signal each 350 Hz,~3 packets\\n#  will be received.\\n# backgroundTimeBetweenScans: Same than foregroundTimeBetweenScans, but when device is in the background.\\n#  this is the most important setting in terms of battery consumption.\\n# backgroundScanDuration: Same than foregroundScanDuration but in background.\\n\\n# Uncomment these parameters in case you want to use a Custom profile\\n\\n# foregroundTimeBetweenScans = 3300\\n# foregroundScanDuration = 3300\\n# backgroundTimeBetweenScans = 60000\\n# backgroundScanDuration = 5001\\n\\n# MOCA Beacon detection settings (approximate distance in meters)\\n# distance detection is strongly dependent on hardware, and device calibration.\\n# Parameter indicates the threshold for the next zone, starting in 0\\n# Default config: 0-1m: immediate, 1m-5m: immediate, >5m far\\n# Uncomment the following lines if you want to override this settings.\\n\\n# proximityImmediate= 1\\n# proximityNear = 5\\n\\n# Required for Wi-Fi beacon detection. If your project does not include detecting\\n# Wi-Fi Beacons, comment out the following line\\nwifiProximity = true\\n\\n# ACTIVE_SCANNING: When a user gets into a geofence that contains Wi-Fi beacons\\n# MOCA SDK performs a Wi-Fi scan once every 60 seconds in background and once # every 30 seconds in  foreground.\\n# PASSIVE_SCANNING: SDK will never initiate any Wi-Fi Scan. But if another app\\n# or the systems performs a Wi-Fi Scanning, the SDK will use this information\\n# to determine if the device is nearby a Wi-Fi Beacon.\\nwifiScanningMode = ACTIVE_SCANNING\\n\\n#Other settings\\n\\n#Used to delay load of HTML overlay until App is ready to show it.\\n#experienceOverlay.delayAfterNotificationTapMs = 1000\\n\\n#Cache in MB\\ncacheSize = 100\\n\\n#Data fetch interval in milliseconds. Defaults to 1 hour\\ndataFetchInterval = 3600000\\n\\n#Event upload interval. Defaults to 15 minutes.\\neventUploadInterval = 900000\\n\\nmoca.CUSTOM_PUSH_ICON = @drawable/ic_moca_logo\\n\\n\",\n      \"language\": \"ruby\",\n      \"name\": \"MOCA.properties\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Initializing MOCA in the Application class\"\n}\n[/block]\nWe are ready to initialize MOCA SDK!\n\nMOCA SDK must be initialized in the `onCreate()` method of your **Application** class:\n\n1 - If you don't have one, create a new class that inherits from Application. You will need to declare the name of this class in the `AndroidManifest.xml` file. As you can see in the AndroidManifest.xml section above.\n2 - Import `com.innoquant.moca.*` package into your main **Application** class.\n3 - Initialize MOCA SDK in the `onCreate` method of this class.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\npublic class MocaApplication extends Application {\\n\\n    @Override\\n    public void onCreate() {\\n        super.onCreate();\\n\\n        // Init MOCA library\\n        MOCA.initializeSDK(this);\\n    }\\n}\\n\",\n      \"language\": \"java\",\n      \"name\": \"MocaApplication.java\"\n    }\n  ]\n}\n[/block]\n4 - Declare the Application class in your app `AndroidManifest.xml`\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/F3KObXES3CnfPRbMGWbE_android-name-red.gif\",\n        \"android-name-red.gif\",\n        \"630\",\n        \"243\",\n        \"#0f344c\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Do not initialize MOCA within an Activity\",\n  \"body\": \"By doing so, MOCA won't be able to manage background events.\"\n}\n[/block]","createdAt":"2015-07-17T15:41:33.472Z","githubsync":"","isReference":false,"parentDoc":null,"sync_unique":"","title":"Configuration","api":{"auth":"required","params":[],"url":"","results":{"codes":[{"code":"{}","language":"json","status":200,"name":""},{"name":"","code":"{}","language":"json","status":400}]},"settings":""},"updates":["5716177840ef9c2000cac8d2","57602f88c811102000cef2fe"],"user":"559a618bdbcfd20d00710b38","type":"basic","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Configuration


[block:api-header] { "type": "basic", "title": "Grab your AppKey and AppSecret" } [/block] 1 - Go to [https://console.mocaplatform.com](https://console.mocaplatform.com) and sign into your MOCA account. 2 - Select Apps item at left sidebar, and then click + New App in the content panel. Fill in the form and complete the app creation. 3 - Open the newly created app and navigate to Settings item. Select API keys tab. 4 - Get `App Key` and `App Secret`. [block:image] { "images": [ { "image": [ "https://files.readme.io/jvi2iXdScWdM4W428eiX_consolekeys.png", "consolekeys.png", "704", "458", "#b02428", "" ] } ] } [/block] You can configure the MOCA SDK from the `AndroidManifest.xml` file, or alternatively from a `MOCA.properties` file [block:api-header] { "type": "basic", "title": "MOCA.properties file" } [/block] Starting from MOCA Android SDK 1.9.0, you can configure the SDK using a `MOCA.properties` file. 1 - Create an `assets` folder, just inside your App's main folder. [block:image] { "images": [ { "image": [ "https://files.readme.io/1k7sOod6QFGfMreUtwCl_assets-folder.png", "assets-folder.png", "700", "598", "#5a8fce", "" ] } ] } [/block] You should be able to see a new folder in your project. [block:image] { "images": [ { "image": [ "https://files.readme.io/9IgnTA5oSDqOMtqk5Xw0_assets.png", "assets.png", "272", "272", "#4d87d1", "" ] } ] } [/block] 2 - Create a file called `MOCA.properties` by right clicking the `assets` folder and selecting New > File. 3 - Configure the SDK with the necessary keys. Please bear in mind that ***the only mandatory keys are AppKey, and AppSecret***. The ***gcmSender*** is mandatory only if you want to use MOCA Remote Push Notifications service. [block:callout] { "type": "info", "title": "Get your GCM Sender from Google", "body": "Check [this guide](./gcm-fcm-cloud-messaging-setup) in order to get your Cloud Messaging Sender Id." } [/block] [block:callout] { "type": "warning", "title": "", "body": "Don't forget to paste the AppKey and AppSecret with the ones corresponding to your App. Otherwise the SDK won't be able to connect to MOCA Cloud." } [/block] Contents of the `MOCA.properties` file: [block:code] { "codes": [ { "code": "#MOCA App key and app secret. You can get this keys from the MOCA Console.\nappKey = YOUR-MOCA-APP-KEY\nappSecret = YOUR-MOCA-APP-SECRET\n\n#MOCA SDK Log level. Possible values [Off, Error, Warning, Info, Debug, Verbose]\nlogLevel = Debug\n\n# MOCA Remote Push Notifications\n# disable it if you have your own/ other remote push implementation\nremotePushNotificationsService = true\n\n# MOCA Proximity Service includes beacon and geofence detection\nproximityService = true\n\n# MOCA GeoTracking Service generates geo points periodically for analytics\ngeoTrackingService = true\n\n# MOCA Event Tracking Service. If enabled, activates event tracking (Sessions, custom events etc.)\neventTrackingService = true\n\n# MOCA driver. This is required for Bluetooth Beacon detection. Set it to false if a custom\n# beacon driver is being used\nmocaDriver = true\n\n# Background location. Allows geoTracking in background\nbackgroundLocation = true\n\n# GCM Sender ID. Only needed if you are using MOCA Remote Push Notifications.\ngcmSender = YOUR-GCM-SENDER-ID\n\n# Beacon detection engine profile [LowLatency, Balanced, BatterySaver, Custom]\n# LowLatency = Notifications will be delivered almost instantly in foreground and background.\n# but will have an important impact on the user's device battery.\n# Balanced = Notifications are delivered almost instantly in foreground. In background it can\n# take up to one minute. In Android Lollipop, Marshmallow, and N there are operating system\n# optimizations that reduce the notification delay (Default setting).\n# BatterySaver = Detections in foreground can take up to one minute, and in background up to\n#5 minutes. this is the recommended setting for analytics-only usages.\n# \nbeaconProfile = Balanced\n\n# If beaconProfile is \"Custom\", the following parameters are mandatory\n# foregroundTimeBetweenScans: Time between each scan in milliseconds, close scans means faster response, but\n# more battery consumption.\n# foregroundScanDuration: Time while device will be listening bluetooth signals in milliseconds.\n# We recommend at least 1100 ms, so if your beacon broadcasts a signal each 350 Hz,~3 packets\n# will be received.\n# backgroundTimeBetweenScans: Same than foregroundTimeBetweenScans, but when device is in the background.\n# this is the most important setting in terms of battery consumption.\n# backgroundScanDuration: Same than foregroundScanDuration but in background.\n\n# Uncomment these parameters in case you want to use a Custom profile\n\n# foregroundTimeBetweenScans = 3300\n# foregroundScanDuration = 3300\n# backgroundTimeBetweenScans = 60000\n# backgroundScanDuration = 5001\n\n# MOCA Beacon detection settings (approximate distance in meters)\n# distance detection is strongly dependent on hardware, and device calibration.\n# Parameter indicates the threshold for the next zone, starting in 0\n# Default config: 0-1m: immediate, 1m-5m: immediate, >5m far\n# Uncomment the following lines if you want to override this settings.\n\n# proximityImmediate= 1\n# proximityNear = 5\n\n# Required for Wi-Fi beacon detection. If your project does not include detecting\n# Wi-Fi Beacons, comment out the following line\nwifiProximity = true\n\n# ACTIVE_SCANNING: When a user gets into a geofence that contains Wi-Fi beacons\n# MOCA SDK performs a Wi-Fi scan once every 60 seconds in background and once # every 30 seconds in  foreground.\n# PASSIVE_SCANNING: SDK will never initiate any Wi-Fi Scan. But if another app\n# or the systems performs a Wi-Fi Scanning, the SDK will use this information\n# to determine if the device is nearby a Wi-Fi Beacon.\nwifiScanningMode = ACTIVE_SCANNING\n\n#Other settings\n\n#Used to delay load of HTML overlay until App is ready to show it.\n#experienceOverlay.delayAfterNotificationTapMs = 1000\n\n#Cache in MB\ncacheSize = 100\n\n#Data fetch interval in milliseconds. Defaults to 1 hour\ndataFetchInterval = 3600000\n\n#Event upload interval. Defaults to 15 minutes.\neventUploadInterval = 900000\n\nmoca.CUSTOM_PUSH_ICON = @drawable/ic_moca_logo\n\n", "language": "ruby", "name": "MOCA.properties" } ] } [/block] [block:api-header] { "type": "basic", "title": "Initializing MOCA in the Application class" } [/block] We are ready to initialize MOCA SDK! MOCA SDK must be initialized in the `onCreate()` method of your **Application** class: 1 - If you don't have one, create a new class that inherits from Application. You will need to declare the name of this class in the `AndroidManifest.xml` file. As you can see in the AndroidManifest.xml section above. 2 - Import `com.innoquant.moca.*` package into your main **Application** class. 3 - Initialize MOCA SDK in the `onCreate` method of this class. [block:code] { "codes": [ { "code": "\npublic class MocaApplication extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n // Init MOCA library\n MOCA.initializeSDK(this);\n }\n}\n", "language": "java", "name": "MocaApplication.java" } ] } [/block] 4 - Declare the Application class in your app `AndroidManifest.xml` [block:image] { "images": [ { "image": [ "https://files.readme.io/F3KObXES3CnfPRbMGWbE_android-name-red.gif", "android-name-red.gif", "630", "243", "#0f344c", "" ] } ] } [/block] [block:callout] { "type": "danger", "title": "Do not initialize MOCA within an Activity", "body": "By doing so, MOCA won't be able to manage background events." } [/block]
[block:api-header] { "type": "basic", "title": "Grab your AppKey and AppSecret" } [/block] 1 - Go to [https://console.mocaplatform.com](https://console.mocaplatform.com) and sign into your MOCA account. 2 - Select Apps item at left sidebar, and then click + New App in the content panel. Fill in the form and complete the app creation. 3 - Open the newly created app and navigate to Settings item. Select API keys tab. 4 - Get `App Key` and `App Secret`. [block:image] { "images": [ { "image": [ "https://files.readme.io/jvi2iXdScWdM4W428eiX_consolekeys.png", "consolekeys.png", "704", "458", "#b02428", "" ] } ] } [/block] You can configure the MOCA SDK from the `AndroidManifest.xml` file, or alternatively from a `MOCA.properties` file [block:api-header] { "type": "basic", "title": "MOCA.properties file" } [/block] Starting from MOCA Android SDK 1.9.0, you can configure the SDK using a `MOCA.properties` file. 1 - Create an `assets` folder, just inside your App's main folder. [block:image] { "images": [ { "image": [ "https://files.readme.io/1k7sOod6QFGfMreUtwCl_assets-folder.png", "assets-folder.png", "700", "598", "#5a8fce", "" ] } ] } [/block] You should be able to see a new folder in your project. [block:image] { "images": [ { "image": [ "https://files.readme.io/9IgnTA5oSDqOMtqk5Xw0_assets.png", "assets.png", "272", "272", "#4d87d1", "" ] } ] } [/block] 2 - Create a file called `MOCA.properties` by right clicking the `assets` folder and selecting New > File. 3 - Configure the SDK with the necessary keys. Please bear in mind that ***the only mandatory keys are AppKey, and AppSecret***. The ***gcmSender*** is mandatory only if you want to use MOCA Remote Push Notifications service. [block:callout] { "type": "info", "title": "Get your GCM Sender from Google", "body": "Check [this guide](./gcm-fcm-cloud-messaging-setup) in order to get your Cloud Messaging Sender Id." } [/block] [block:callout] { "type": "warning", "title": "", "body": "Don't forget to paste the AppKey and AppSecret with the ones corresponding to your App. Otherwise the SDK won't be able to connect to MOCA Cloud." } [/block] Contents of the `MOCA.properties` file: [block:code] { "codes": [ { "code": "#MOCA App key and app secret. You can get this keys from the MOCA Console.\nappKey = YOUR-MOCA-APP-KEY\nappSecret = YOUR-MOCA-APP-SECRET\n\n#MOCA SDK Log level. Possible values [Off, Error, Warning, Info, Debug, Verbose]\nlogLevel = Debug\n\n# MOCA Remote Push Notifications\n# disable it if you have your own/ other remote push implementation\nremotePushNotificationsService = true\n\n# MOCA Proximity Service includes beacon and geofence detection\nproximityService = true\n\n# MOCA GeoTracking Service generates geo points periodically for analytics\ngeoTrackingService = true\n\n# MOCA Event Tracking Service. If enabled, activates event tracking (Sessions, custom events etc.)\neventTrackingService = true\n\n# MOCA driver. This is required for Bluetooth Beacon detection. Set it to false if a custom\n# beacon driver is being used\nmocaDriver = true\n\n# Background location. Allows geoTracking in background\nbackgroundLocation = true\n\n# GCM Sender ID. Only needed if you are using MOCA Remote Push Notifications.\ngcmSender = YOUR-GCM-SENDER-ID\n\n# Beacon detection engine profile [LowLatency, Balanced, BatterySaver, Custom]\n# LowLatency = Notifications will be delivered almost instantly in foreground and background.\n# but will have an important impact on the user's device battery.\n# Balanced = Notifications are delivered almost instantly in foreground. In background it can\n# take up to one minute. In Android Lollipop, Marshmallow, and N there are operating system\n# optimizations that reduce the notification delay (Default setting).\n# BatterySaver = Detections in foreground can take up to one minute, and in background up to\n#5 minutes. this is the recommended setting for analytics-only usages.\n# \nbeaconProfile = Balanced\n\n# If beaconProfile is \"Custom\", the following parameters are mandatory\n# foregroundTimeBetweenScans: Time between each scan in milliseconds, close scans means faster response, but\n# more battery consumption.\n# foregroundScanDuration: Time while device will be listening bluetooth signals in milliseconds.\n# We recommend at least 1100 ms, so if your beacon broadcasts a signal each 350 Hz,~3 packets\n# will be received.\n# backgroundTimeBetweenScans: Same than foregroundTimeBetweenScans, but when device is in the background.\n# this is the most important setting in terms of battery consumption.\n# backgroundScanDuration: Same than foregroundScanDuration but in background.\n\n# Uncomment these parameters in case you want to use a Custom profile\n\n# foregroundTimeBetweenScans = 3300\n# foregroundScanDuration = 3300\n# backgroundTimeBetweenScans = 60000\n# backgroundScanDuration = 5001\n\n# MOCA Beacon detection settings (approximate distance in meters)\n# distance detection is strongly dependent on hardware, and device calibration.\n# Parameter indicates the threshold for the next zone, starting in 0\n# Default config: 0-1m: immediate, 1m-5m: immediate, >5m far\n# Uncomment the following lines if you want to override this settings.\n\n# proximityImmediate= 1\n# proximityNear = 5\n\n# Required for Wi-Fi beacon detection. If your project does not include detecting\n# Wi-Fi Beacons, comment out the following line\nwifiProximity = true\n\n# ACTIVE_SCANNING: When a user gets into a geofence that contains Wi-Fi beacons\n# MOCA SDK performs a Wi-Fi scan once every 60 seconds in background and once # every 30 seconds in  foreground.\n# PASSIVE_SCANNING: SDK will never initiate any Wi-Fi Scan. But if another app\n# or the systems performs a Wi-Fi Scanning, the SDK will use this information\n# to determine if the device is nearby a Wi-Fi Beacon.\nwifiScanningMode = ACTIVE_SCANNING\n\n#Other settings\n\n#Used to delay load of HTML overlay until App is ready to show it.\n#experienceOverlay.delayAfterNotificationTapMs = 1000\n\n#Cache in MB\ncacheSize = 100\n\n#Data fetch interval in milliseconds. Defaults to 1 hour\ndataFetchInterval = 3600000\n\n#Event upload interval. Defaults to 15 minutes.\neventUploadInterval = 900000\n\nmoca.CUSTOM_PUSH_ICON = @drawable/ic_moca_logo\n\n", "language": "ruby", "name": "MOCA.properties" } ] } [/block] [block:api-header] { "type": "basic", "title": "Initializing MOCA in the Application class" } [/block] We are ready to initialize MOCA SDK! MOCA SDK must be initialized in the `onCreate()` method of your **Application** class: 1 - If you don't have one, create a new class that inherits from Application. You will need to declare the name of this class in the `AndroidManifest.xml` file. As you can see in the AndroidManifest.xml section above. 2 - Import `com.innoquant.moca.*` package into your main **Application** class. 3 - Initialize MOCA SDK in the `onCreate` method of this class. [block:code] { "codes": [ { "code": "\npublic class MocaApplication extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n // Init MOCA library\n MOCA.initializeSDK(this);\n }\n}\n", "language": "java", "name": "MocaApplication.java" } ] } [/block] 4 - Declare the Application class in your app `AndroidManifest.xml` [block:image] { "images": [ { "image": [ "https://files.readme.io/F3KObXES3CnfPRbMGWbE_android-name-red.gif", "android-name-red.gif", "630", "243", "#0f344c", "" ] } ] } [/block] [block:callout] { "type": "danger", "title": "Do not initialize MOCA within an Activity", "body": "By doing so, MOCA won't be able to manage background events." } [/block]
{"_id":"5f998577fb81e800451c0323","user":"559a618bdbcfd20d00710b38","excerpt":"","githubsync":"","title":"Remote Push Notifications","type":"basic","updates":[],"body":"[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Migration from GCM to FCM\",\n  \"body\": \"As you may already now, Google has deprecated GCM and only supports FCM.\\nIf you are about to update the MOCA SDK for Android from version prior 2.11.2 or earlier to version 2.12.0 or greater, please ensure that you are no longer using GCM for **any** other feature in your application. \\nAlthough Google still supports both APIs for versions Android 10 and before, **you cannot have both GCM and FCM in the same app**. If you do, it could potentially generate different push tokens (one for GCM and one for FCM), and from our observations, when that happens the GCM token gets invalidated without any warning.\\nPlease note that the MOCA SDK does not use GCM in any way.\"\n}\n[/block]\nMOCA SDK easily integrates with FCM push notifications.\n\n- FCM token is automatically requested if you activate this feature.\n- Push notifications are automatically handled by the library.\n- Tracked received push notifications with MOCA SDK. \n- The tracked data can be analyzed in MOCA Analytics \u000b(Pushes, PushOpened, and more) -\n \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"remotePushNotificationsService = true\",\n      \"language\": \"ruby\",\n      \"name\": \"MOCA.properties\"\n    },\n    {\n      \"code\": \" <application …>\\n\\n\\t<meta-data android:name=\\\"moca.AUTOMATIC_PUSH_SETUP_ENABLED\\\" android:value=\\\"true\\\"/>\",\n      \"language\": \"xml\",\n      \"name\": \"AndroidManifest.xml\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Integrating Push with MOCA\"\n}\n[/block]\nThis receiver will handle registration process and incoming push notification messages generated by MOCA.\n\n- Ensure you have added your Google Sender Id:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"gcmSender = YOUR-GCM-SENDER-ID\",\n      \"language\": \"ruby\",\n      \"name\": \"MOCA.properties\"\n    },\n    {\n      \"code\": \" <!--Optional: Include it for remote push notifications-->\\n    <!--Be careful with the space before the number-->\\n    <meta-data android:name=\\\"moca.GCM_SENDER\\\" android:value=\\\"\\\\ YOUR_GCM_SENDER_ID\\\" />\",\n      \"language\": \"xml\",\n      \"name\": \"AndroidManifest.xml\"\n    }\n  ]\n}\n[/block]","slug":"push-notifications","sync_unique":"","version":"5f998577fb81e800451c032f","__v":0,"category":"5f998576fb81e800451c02f5","next":{"pages":[],"description":""},"order":3,"link_url":"","parentDoc":null,"project":"559a61d2dbcfd20d00710b39","api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required","params":[],"url":""},"createdAt":"2015-07-17T17:32:48.053Z","hidden":false,"isReference":false,"link_external":false,"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Remote Push Notifications


[block:callout] { "type": "warning", "title": "Migration from GCM to FCM", "body": "As you may already now, Google has deprecated GCM and only supports FCM.\nIf you are about to update the MOCA SDK for Android from version prior 2.11.2 or earlier to version 2.12.0 or greater, please ensure that you are no longer using GCM for **any** other feature in your application. \nAlthough Google still supports both APIs for versions Android 10 and before, **you cannot have both GCM and FCM in the same app**. If you do, it could potentially generate different push tokens (one for GCM and one for FCM), and from our observations, when that happens the GCM token gets invalidated without any warning.\nPlease note that the MOCA SDK does not use GCM in any way." } [/block] MOCA SDK easily integrates with FCM push notifications. - FCM token is automatically requested if you activate this feature. - Push notifications are automatically handled by the library. - Tracked received push notifications with MOCA SDK. - The tracked data can be analyzed in MOCA Analytics (Pushes, PushOpened, and more) - [block:code] { "codes": [ { "code": "remotePushNotificationsService = true", "language": "ruby", "name": "MOCA.properties" }, { "code": " <application …>\n\n\t<meta-data android:name=\"moca.AUTOMATIC_PUSH_SETUP_ENABLED\" android:value=\"true\"/>", "language": "xml", "name": "AndroidManifest.xml" } ] } [/block] [block:api-header] { "type": "basic", "title": "Integrating Push with MOCA" } [/block] This receiver will handle registration process and incoming push notification messages generated by MOCA. - Ensure you have added your Google Sender Id: [block:code] { "codes": [ { "code": "gcmSender = YOUR-GCM-SENDER-ID", "language": "ruby", "name": "MOCA.properties" }, { "code": " <!--Optional: Include it for remote push notifications-->\n <!--Be careful with the space before the number-->\n <meta-data android:name=\"moca.GCM_SENDER\" android:value=\"\\ YOUR_GCM_SENDER_ID\" />", "language": "xml", "name": "AndroidManifest.xml" } ] } [/block]
[block:callout] { "type": "warning", "title": "Migration from GCM to FCM", "body": "As you may already now, Google has deprecated GCM and only supports FCM.\nIf you are about to update the MOCA SDK for Android from version prior 2.11.2 or earlier to version 2.12.0 or greater, please ensure that you are no longer using GCM for **any** other feature in your application. \nAlthough Google still supports both APIs for versions Android 10 and before, **you cannot have both GCM and FCM in the same app**. If you do, it could potentially generate different push tokens (one for GCM and one for FCM), and from our observations, when that happens the GCM token gets invalidated without any warning.\nPlease note that the MOCA SDK does not use GCM in any way." } [/block] MOCA SDK easily integrates with FCM push notifications. - FCM token is automatically requested if you activate this feature. - Push notifications are automatically handled by the library. - Tracked received push notifications with MOCA SDK. - The tracked data can be analyzed in MOCA Analytics (Pushes, PushOpened, and more) - [block:code] { "codes": [ { "code": "remotePushNotificationsService = true", "language": "ruby", "name": "MOCA.properties" }, { "code": " <application …>\n\n\t<meta-data android:name=\"moca.AUTOMATIC_PUSH_SETUP_ENABLED\" android:value=\"true\"/>", "language": "xml", "name": "AndroidManifest.xml" } ] } [/block] [block:api-header] { "type": "basic", "title": "Integrating Push with MOCA" } [/block] This receiver will handle registration process and incoming push notification messages generated by MOCA. - Ensure you have added your Google Sender Id: [block:code] { "codes": [ { "code": "gcmSender = YOUR-GCM-SENDER-ID", "language": "ruby", "name": "MOCA.properties" }, { "code": " <!--Optional: Include it for remote push notifications-->\n <!--Be careful with the space before the number-->\n <meta-data android:name=\"moca.GCM_SENDER\" android:value=\"\\ YOUR_GCM_SENDER_ID\" />", "language": "xml", "name": "AndroidManifest.xml" } ] } [/block]
{"_id":"5f998577fb81e800451c0324","sync_unique":"","title":"ProGuard rules","updates":[],"__v":0,"githubsync":"","link_external":false,"order":4,"parentDoc":null,"body":"If you use ProGuard, please include the following rules:\n\n```\n-keep class com.innoquant.** { *; }\n-keep class org.msgpack.** { *; }\n-dontwarn org.msgpack.**\n```","createdAt":"2016-03-01T17:53:49.824Z","isReference":false,"slug":"proguard-rules","next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","user":"559a618bdbcfd20d00710b38","type":"basic","version":"5f998577fb81e800451c032f","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]}},"category":"5f998576fb81e800451c02f5","excerpt":"","hidden":false,"link_url":"","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

ProGuard rules


If you use ProGuard, please include the following rules: ``` -keep class com.innoquant.** { *; } -keep class org.msgpack.** { *; } -dontwarn org.msgpack.** ```
If you use ProGuard, please include the following rules: ``` -keep class com.innoquant.** { *; } -keep class org.msgpack.** { *; } -dontwarn org.msgpack.** ```
{"_id":"5f998577fb81e800451c0325","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"status":200,"name":"","code":"{}","language":"json"},{"code":"{}","language":"json","status":400,"name":""}]}},"excerpt":"","link_external":false,"order":5,"user":"559a618bdbcfd20d00710b38","version":"5f998577fb81e800451c032f","__v":0,"body":"Starting from **Android 6.0**, there are some permissions that are considered *dangerous*. All the permissions that fall into this category **are no longer requested at install time, but at Run Time.**\n\n##Android Lollipop and lower\n\n\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/utGBMUxUSWabJudw5kv6_lollipop-permissions.jpg\",\n        \"lollipop-permissions.jpg\",\n        \"630\",\n        \"1120\",\n        \"#6d944b\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n##Android Marshmallow and greater\n\n\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/RZuk8nGtQj6YGS9uik0c_marshmallow-permissions.jpg\",\n        \"marshmallow-permissions.jpg\",\n        \"630\",\n        \"1120\",\n        \"#4aa096\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Requesting permissions at runtime.\"\n}\n[/block]\nMOCA SDK requires the `ACCESS_FINE_LOCATION` permission for **bluetooth** scanning, **location tracking** and **geofencing**.\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Explicit background location permission\",\n  \"body\": \"Since Android 10. It is necessary to explicitly request the `ACCESS_BACKGROUND_LOCATION` permission at run time. If this permission is not explicitly requested, the permission request prompt will only show a \\\"when in use\\\" permission. This prevents MOCA SDK from detecting geofences or bluetooth beacons in the background or when the app is not running.\"\n}\n[/block]\nThis is an example of how to request these permissions.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    private final static String FINE_LOCATION_PERM = Manifest.permission.ACCESS_FINE_LOCATION;\\n    private final static String BACKGROUND_LOCATION_PERM = \\\"android.permission.ACCESS_BACKGROUND_LOCATION\\\";\\n    private static final String[] NEEDED_PERMISSIONS = {FINE_LOCATION_PERM, BACKGROUND_LOCATION_PERM, BACKGROUND_LOCATION_PERM};\\n    private final static int REQUEST_PERMISSION_GEO = 101; //any identifier\\n\\n    public static void requestLocationPermissions(final Activity activity) {\\n        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {\\n            return;\\n        }\\n        if (activity.shouldShowRequestPermissionRationale(BACKGROUND_LOCATION_PERM)) {\\n            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);\\n            builder.setMessage(\\\"The application uses your location in order to help \\\" +\\n                    \\\"you find closest promotions\\\")\\n                    .setTitle(\\\"MOCA\\\")\\n                    .setNeutralButton(\\\"ok\\\",\\n                            (dialog, which) -> activity.requestPermissions(NEEDED_PERMISSIONS,\\n                                    REQUEST_PERMISSION_GEO))\\n                    .show();\\n        } else {\\n            // No explanation needed, we can request the permission.\\n            activity.requestPermissions(NEEDED_PERMISSIONS, REQUEST_PERMISSION_GEO);\\n        }\\n    }\",\n      \"language\": \"java\",\n      \"name\": \"Permission Request example\"\n    }\n  ]\n}\n[/block]\nOnce the user allows or denies the permission, Android will send you this information using the Activity's `onRequestPermissionsResult` method. Override it so you can handle the response.\n\nBelow you will find an example of how to implement this method, and how to initialize the permission-affected MOCA Services:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    /**\\n     * Callback received when a permissions request has been completed.\\n     */\\n    @Override\\n    public void onRequestPermissionsResult(int requestCode, \\n                                           @NonNull String[] permissions,\\n                                           @NonNull int[] grantResults) {\\n        if ((requestCode != REQUEST_PERMISSION_GEO) {\\n            return;\\n        }\\n        if ((grantResults[0] != PackageManager.PERMISSION_GRANTED)) {\\n            Log.e(TAG, \\\"Location permissions denied\\\");\\n        }\\n        if (!MOCA.initialized()) {\\n            return;\\n        }\\n        MOCA.setProximityEnabled(true);\\n        MOCA.setGeoTrackingEnabled(true);\\n    }\",\n      \"language\": \"java\",\n      \"name\": \"Permission request callback\"\n    }\n  ]\n}\n[/block]\nLearn more about [requesting permissions at Run Time.](https://developer.android.com/training/permissions/requesting.html) (external link).","category":"5f998576fb81e800451c02f5","title":"Location permissions","type":"basic","githubsync":"","link_url":"","next":{"pages":[],"description":""},"parentDoc":null,"updates":[],"createdAt":"2016-05-19T09:14:01.099Z","hidden":false,"isReference":false,"project":"559a61d2dbcfd20d00710b39","slug":"android-60-permissions","sync_unique":"","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Location permissions


Starting from **Android 6.0**, there are some permissions that are considered *dangerous*. All the permissions that fall into this category **are no longer requested at install time, but at Run Time.** ##Android Lollipop and lower [block:image] { "images": [ { "image": [ "https://files.readme.io/utGBMUxUSWabJudw5kv6_lollipop-permissions.jpg", "lollipop-permissions.jpg", "630", "1120", "#6d944b", "" ] } ] } [/block] ##Android Marshmallow and greater [block:image] { "images": [ { "image": [ "https://files.readme.io/RZuk8nGtQj6YGS9uik0c_marshmallow-permissions.jpg", "marshmallow-permissions.jpg", "630", "1120", "#4aa096", "" ] } ] } [/block] [block:api-header] { "type": "basic", "title": "Requesting permissions at runtime." } [/block] MOCA SDK requires the `ACCESS_FINE_LOCATION` permission for **bluetooth** scanning, **location tracking** and **geofencing**. [block:callout] { "type": "warning", "title": "Explicit background location permission", "body": "Since Android 10. It is necessary to explicitly request the `ACCESS_BACKGROUND_LOCATION` permission at run time. If this permission is not explicitly requested, the permission request prompt will only show a \"when in use\" permission. This prevents MOCA SDK from detecting geofences or bluetooth beacons in the background or when the app is not running." } [/block] This is an example of how to request these permissions. [block:code] { "codes": [ { "code": " private final static String FINE_LOCATION_PERM = Manifest.permission.ACCESS_FINE_LOCATION;\n private final static String BACKGROUND_LOCATION_PERM = \"android.permission.ACCESS_BACKGROUND_LOCATION\";\n private static final String[] NEEDED_PERMISSIONS = {FINE_LOCATION_PERM, BACKGROUND_LOCATION_PERM, BACKGROUND_LOCATION_PERM};\n private final static int REQUEST_PERMISSION_GEO = 101; //any identifier\n\n public static void requestLocationPermissions(final Activity activity) {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {\n return;\n }\n if (activity.shouldShowRequestPermissionRationale(BACKGROUND_LOCATION_PERM)) {\n final AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n builder.setMessage(\"The application uses your location in order to help \" +\n \"you find closest promotions\")\n .setTitle(\"MOCA\")\n .setNeutralButton(\"ok\",\n (dialog, which) -> activity.requestPermissions(NEEDED_PERMISSIONS,\n REQUEST_PERMISSION_GEO))\n .show();\n } else {\n // No explanation needed, we can request the permission.\n activity.requestPermissions(NEEDED_PERMISSIONS, REQUEST_PERMISSION_GEO);\n }\n }", "language": "java", "name": "Permission Request example" } ] } [/block] Once the user allows or denies the permission, Android will send you this information using the Activity's `onRequestPermissionsResult` method. Override it so you can handle the response. Below you will find an example of how to implement this method, and how to initialize the permission-affected MOCA Services: [block:code] { "codes": [ { "code": " /**\n * Callback received when a permissions request has been completed.\n */\n @Override\n public void onRequestPermissionsResult(int requestCode, \n @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n if ((requestCode != REQUEST_PERMISSION_GEO) {\n return;\n }\n if ((grantResults[0] != PackageManager.PERMISSION_GRANTED)) {\n Log.e(TAG, \"Location permissions denied\");\n }\n if (!MOCA.initialized()) {\n return;\n }\n MOCA.setProximityEnabled(true);\n MOCA.setGeoTrackingEnabled(true);\n }", "language": "java", "name": "Permission request callback" } ] } [/block] Learn more about [requesting permissions at Run Time.](https://developer.android.com/training/permissions/requesting.html) (external link).
Starting from **Android 6.0**, there are some permissions that are considered *dangerous*. All the permissions that fall into this category **are no longer requested at install time, but at Run Time.** ##Android Lollipop and lower [block:image] { "images": [ { "image": [ "https://files.readme.io/utGBMUxUSWabJudw5kv6_lollipop-permissions.jpg", "lollipop-permissions.jpg", "630", "1120", "#6d944b", "" ] } ] } [/block] ##Android Marshmallow and greater [block:image] { "images": [ { "image": [ "https://files.readme.io/RZuk8nGtQj6YGS9uik0c_marshmallow-permissions.jpg", "marshmallow-permissions.jpg", "630", "1120", "#4aa096", "" ] } ] } [/block] [block:api-header] { "type": "basic", "title": "Requesting permissions at runtime." } [/block] MOCA SDK requires the `ACCESS_FINE_LOCATION` permission for **bluetooth** scanning, **location tracking** and **geofencing**. [block:callout] { "type": "warning", "title": "Explicit background location permission", "body": "Since Android 10. It is necessary to explicitly request the `ACCESS_BACKGROUND_LOCATION` permission at run time. If this permission is not explicitly requested, the permission request prompt will only show a \"when in use\" permission. This prevents MOCA SDK from detecting geofences or bluetooth beacons in the background or when the app is not running." } [/block] This is an example of how to request these permissions. [block:code] { "codes": [ { "code": " private final static String FINE_LOCATION_PERM = Manifest.permission.ACCESS_FINE_LOCATION;\n private final static String BACKGROUND_LOCATION_PERM = \"android.permission.ACCESS_BACKGROUND_LOCATION\";\n private static final String[] NEEDED_PERMISSIONS = {FINE_LOCATION_PERM, BACKGROUND_LOCATION_PERM, BACKGROUND_LOCATION_PERM};\n private final static int REQUEST_PERMISSION_GEO = 101; //any identifier\n\n public static void requestLocationPermissions(final Activity activity) {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {\n return;\n }\n if (activity.shouldShowRequestPermissionRationale(BACKGROUND_LOCATION_PERM)) {\n final AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n builder.setMessage(\"The application uses your location in order to help \" +\n \"you find closest promotions\")\n .setTitle(\"MOCA\")\n .setNeutralButton(\"ok\",\n (dialog, which) -> activity.requestPermissions(NEEDED_PERMISSIONS,\n REQUEST_PERMISSION_GEO))\n .show();\n } else {\n // No explanation needed, we can request the permission.\n activity.requestPermissions(NEEDED_PERMISSIONS, REQUEST_PERMISSION_GEO);\n }\n }", "language": "java", "name": "Permission Request example" } ] } [/block] Once the user allows or denies the permission, Android will send you this information using the Activity's `onRequestPermissionsResult` method. Override it so you can handle the response. Below you will find an example of how to implement this method, and how to initialize the permission-affected MOCA Services: [block:code] { "codes": [ { "code": " /**\n * Callback received when a permissions request has been completed.\n */\n @Override\n public void onRequestPermissionsResult(int requestCode, \n @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n if ((requestCode != REQUEST_PERMISSION_GEO) {\n return;\n }\n if ((grantResults[0] != PackageManager.PERMISSION_GRANTED)) {\n Log.e(TAG, \"Location permissions denied\");\n }\n if (!MOCA.initialized()) {\n return;\n }\n MOCA.setProximityEnabled(true);\n MOCA.setGeoTrackingEnabled(true);\n }", "language": "java", "name": "Permission request callback" } ] } [/block] Learn more about [requesting permissions at Run Time.](https://developer.android.com/training/permissions/requesting.html) (external link).
{"_id":"5fe0bfa550d86b006d5df558","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Additional settings","type":"basic","slug":"additional-settings-android","excerpt":"","body":"[block:api-header]\n{\n  \"title\": \"Mute notifications\"\n}\n[/block]\nIf for any reason you want to mute the MOCA generated notifications (for example by adding a switch within your application settings). Call the following method\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.muteNotifications(true)\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nThis setting is persisted between app restarts. In order to restore the SDK to its normal state, call the same method with a `false` argument.\n\nIn order to check the status of this setting, call:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.areNotificationsMuted()\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Geofence and beacon detection\"\n}\n[/block]\nCall the following method with the correct argument in order to enable or disable geofences and bluetooth beacon detection.\n\n- `true`: Enables the feature.\n- `false`: Disables the feature.\nThis setting is persisted across app restarts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setProximityEnabled(true)\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA setProximityEnabled:YES]\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Geolocation tracking\"\n}\n[/block]\nWhen disabled, this prevents the SDK from sending user locations for Analytics\n\n- `true` Enables the feature.\n- `false`: Disables the feature.\nThis setting is persisted across app restarts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setGeoTrackingEnabled(true)\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Wi-Fi Only data synchronization\"\n}\n[/block]\nWhen active, this setting prevents the SDK from downloading and uploading data when using cellular data. This is useful if your application \n\n- `true`: Enables the feature.\n- `false`: Disables the feature.\nThis setting is persisted across app restarts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" MOCA.setWifiOnlyEnabled(true)\\n\",\n      \"language\": \"swift\"\n    },\n    {\n      \"code\": \"[MOCA setWifiOnlyEnabled:YES];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","updates":[],"order":6,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T15:30:45.072Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Additional settings


[block:api-header] { "title": "Mute notifications" } [/block] If for any reason you want to mute the MOCA generated notifications (for example by adding a switch within your application settings). Call the following method [block:code] { "codes": [ { "code": "MOCA.muteNotifications(true)", "language": "java" } ] } [/block] This setting is persisted between app restarts. In order to restore the SDK to its normal state, call the same method with a `false` argument. In order to check the status of this setting, call: [block:code] { "codes": [ { "code": "MOCA.areNotificationsMuted()", "language": "java" } ] } [/block] [block:api-header] { "title": "Geofence and beacon detection" } [/block] Call the following method with the correct argument in order to enable or disable geofences and bluetooth beacon detection. - `true`: Enables the feature. - `false`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setProximityEnabled(true)", "language": "swift" }, { "code": "[MOCA setProximityEnabled:YES]", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Geolocation tracking" } [/block] When disabled, this prevents the SDK from sending user locations for Analytics - `true` Enables the feature. - `false`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true)", "language": "swift" } ] } [/block] [block:api-header] { "title": "Wi-Fi Only data synchronization" } [/block] When active, this setting prevents the SDK from downloading and uploading data when using cellular data. This is useful if your application - `true`: Enables the feature. - `false`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": " MOCA.setWifiOnlyEnabled(true)\n", "language": "swift" }, { "code": "[MOCA setWifiOnlyEnabled:YES];", "language": "objectivec" } ] } [/block]
[block:api-header] { "title": "Mute notifications" } [/block] If for any reason you want to mute the MOCA generated notifications (for example by adding a switch within your application settings). Call the following method [block:code] { "codes": [ { "code": "MOCA.muteNotifications(true)", "language": "java" } ] } [/block] This setting is persisted between app restarts. In order to restore the SDK to its normal state, call the same method with a `false` argument. In order to check the status of this setting, call: [block:code] { "codes": [ { "code": "MOCA.areNotificationsMuted()", "language": "java" } ] } [/block] [block:api-header] { "title": "Geofence and beacon detection" } [/block] Call the following method with the correct argument in order to enable or disable geofences and bluetooth beacon detection. - `true`: Enables the feature. - `false`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setProximityEnabled(true)", "language": "swift" }, { "code": "[MOCA setProximityEnabled:YES]", "language": "objectivec" } ] } [/block] [block:api-header] { "title": "Geolocation tracking" } [/block] When disabled, this prevents the SDK from sending user locations for Analytics - `true` Enables the feature. - `false`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true)", "language": "swift" } ] } [/block] [block:api-header] { "title": "Wi-Fi Only data synchronization" } [/block] When active, this setting prevents the SDK from downloading and uploading data when using cellular data. This is useful if your application - `true`: Enables the feature. - `false`: Disables the feature. This setting is persisted across app restarts. [block:code] { "codes": [ { "code": " MOCA.setWifiOnlyEnabled(true)\n", "language": "swift" }, { "code": "[MOCA setWifiOnlyEnabled:YES];", "language": "objectivec" } ] } [/block]
{"_id":"5f998577fb81e800451c0327","parentDoc":null,"sync_unique":"","updates":[],"githubsync":"","link_url":"","slug":"gcm-fcm-cloud-messaging-setup","api":{"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[]},"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Firebase Messaging\",\n  \"body\": \"Google has integrated Google Cloud Messaging (GCM) into Firebase. API Keys generated through Google API Console are no longer valid.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Enabling Cloud Messaging and generating Server API Key\"\n}\n[/block]\n1 - Sign in into [Google Firebase](https://console.firebase.google.com/)\n2 - Select `CREATE A NEW PROJECT`. \n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"You can also import an existing GCM project using the option below the button.\"\n}\n[/block]\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/e2361bc-Firebase-1.png\",\n        \"Firebase-1.png\",\n        717,\n        509,\n        \"#167cbd\"\n      ]\n    }\n  ]\n}\n[/block]\n3 - Type a name for your new project and select your country.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/ceac511-country-name.png\",\n        \"country-name.png\",\n        688,\n        502,\n        \"#8a8a8a\"\n      ]\n    }\n  ]\n}\n[/block]\n4 - After the project has been created, click on the gear icon and select \"Project settings\"\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/f06c749-project_settings.png\",\n        \"project settings.png\",\n        715,\n        485,\n        \"#0e91cd\"\n      ]\n    }\n  ]\n}\n[/block]\n5 - Select `CLOUD MESSAGING`. Here you will see two keys:\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/d484dbe-keys.png\",\n        \"keys.png\",\n        674,\n        397,\n        \"#0593dc\"\n      ]\n    }\n  ]\n}\n[/block]\n- The **Server Key** is needed to configure the service in the MOCA Console.\n- The **Sender ID** should be used for the [Android SDK configuration](./moca-android-sdk-configuration). (also known as GCM Sender Id).\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Using the Key in the MOCA Console.\"\n}\n[/block]\n1 - [Log in to your MOCA Account](https://console.mocaplatform.com/) and go to Apps **>** *app_to_be_configured* ** >** Settings **>** Services\n2 - Select `Add` in Google Cloud Messaging (GCM) and paste your server API Key there \n\n![](https://files.readme.io/da9ff5b-APi-server-key-moca.png)\n\n- All done. You can now start sending notifications to your users using MOCA Platform to your Android users.","hidden":false,"isReference":false,"order":7,"project":"559a61d2dbcfd20d00710b39","type":"basic","user":"559a618bdbcfd20d00710b38","version":"5f998577fb81e800451c032f","__v":0,"category":"5f998576fb81e800451c02f5","createdAt":"2016-09-13T15:55:17.844Z","excerpt":"","link_external":false,"next":{"pages":[],"description":""},"title":"GCM / FCM: Cloud Messaging Setup.","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

GCM / FCM: Cloud Messaging Setup.


[block:callout] { "type": "info", "title": "Firebase Messaging", "body": "Google has integrated Google Cloud Messaging (GCM) into Firebase. API Keys generated through Google API Console are no longer valid." } [/block] [block:api-header] { "type": "basic", "title": "Enabling Cloud Messaging and generating Server API Key" } [/block] 1 - Sign in into [Google Firebase](https://console.firebase.google.com/) 2 - Select `CREATE A NEW PROJECT`. [block:callout] { "type": "warning", "body": "You can also import an existing GCM project using the option below the button." } [/block] [block:image] { "images": [ { "image": [ "https://files.readme.io/e2361bc-Firebase-1.png", "Firebase-1.png", 717, 509, "#167cbd" ] } ] } [/block] 3 - Type a name for your new project and select your country. [block:image] { "images": [ { "image": [ "https://files.readme.io/ceac511-country-name.png", "country-name.png", 688, 502, "#8a8a8a" ] } ] } [/block] 4 - After the project has been created, click on the gear icon and select "Project settings" [block:image] { "images": [ { "image": [ "https://files.readme.io/f06c749-project_settings.png", "project settings.png", 715, 485, "#0e91cd" ] } ] } [/block] 5 - Select `CLOUD MESSAGING`. Here you will see two keys: [block:image] { "images": [ { "image": [ "https://files.readme.io/d484dbe-keys.png", "keys.png", 674, 397, "#0593dc" ] } ] } [/block] - The **Server Key** is needed to configure the service in the MOCA Console. - The **Sender ID** should be used for the [Android SDK configuration](./moca-android-sdk-configuration). (also known as GCM Sender Id). [block:api-header] { "type": "basic", "title": "Using the Key in the MOCA Console." } [/block] 1 - [Log in to your MOCA Account](https://console.mocaplatform.com/) and go to Apps **>** *app_to_be_configured* ** >** Settings **>** Services 2 - Select `Add` in Google Cloud Messaging (GCM) and paste your server API Key there ![](https://files.readme.io/da9ff5b-APi-server-key-moca.png) - All done. You can now start sending notifications to your users using MOCA Platform to your Android users.
[block:callout] { "type": "info", "title": "Firebase Messaging", "body": "Google has integrated Google Cloud Messaging (GCM) into Firebase. API Keys generated through Google API Console are no longer valid." } [/block] [block:api-header] { "type": "basic", "title": "Enabling Cloud Messaging and generating Server API Key" } [/block] 1 - Sign in into [Google Firebase](https://console.firebase.google.com/) 2 - Select `CREATE A NEW PROJECT`. [block:callout] { "type": "warning", "body": "You can also import an existing GCM project using the option below the button." } [/block] [block:image] { "images": [ { "image": [ "https://files.readme.io/e2361bc-Firebase-1.png", "Firebase-1.png", 717, 509, "#167cbd" ] } ] } [/block] 3 - Type a name for your new project and select your country. [block:image] { "images": [ { "image": [ "https://files.readme.io/ceac511-country-name.png", "country-name.png", 688, 502, "#8a8a8a" ] } ] } [/block] 4 - After the project has been created, click on the gear icon and select "Project settings" [block:image] { "images": [ { "image": [ "https://files.readme.io/f06c749-project_settings.png", "project settings.png", 715, 485, "#0e91cd" ] } ] } [/block] 5 - Select `CLOUD MESSAGING`. Here you will see two keys: [block:image] { "images": [ { "image": [ "https://files.readme.io/d484dbe-keys.png", "keys.png", 674, 397, "#0593dc" ] } ] } [/block] - The **Server Key** is needed to configure the service in the MOCA Console. - The **Sender ID** should be used for the [Android SDK configuration](./moca-android-sdk-configuration). (also known as GCM Sender Id). [block:api-header] { "type": "basic", "title": "Using the Key in the MOCA Console." } [/block] 1 - [Log in to your MOCA Account](https://console.mocaplatform.com/) and go to Apps **>** *app_to_be_configured* ** >** Settings **>** Services 2 - Select `Add` in Google Cloud Messaging (GCM) and paste your server API Key there ![](https://files.readme.io/da9ff5b-APi-server-key-moca.png) - All done. You can now start sending notifications to your users using MOCA Platform to your Android users.
{"_id":"5fe0c02707988f003697efe9","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","params":[],"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":""},"next":{"description":"","pages":[]},"title":"Instance API Android","type":"basic","slug":"instance-api-android","excerpt":"","body":"- The app `Instance object` is a local representation of an app instance downloaded and installed in a user device. It contains the anonymous user profile.\n\n- The instance object is **automatically managed** by MOCA. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAInstance instance = MOCA.getInstance();\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n- The instance object holds a **collection of properties**. Property-value pairs can be set and retrieved and are persisted between app sessions.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n * Sets the value for the given property name.\\n * \\n * @param value Value to be set. It must belong to one of the accepted classes.\\n * @param key Property name.\\n */\\n public void setProperty(String key, Object value);\\n\\n /**\\n * Gets the value for the given property.\\n *\\n * @param key Property name.\\n * @return Value associated with the key or <code>null</code> if none.\\n */\\n public Object getProperty(String key);\\n \",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n- Each instance object is persisted both locally and in the cloud. The instance is automatically uploaded to the cloud each time the app starts.\n- The instance can be saved manually to the cloud. All saves are asynchronous.\n- It is recommended to perform as many sets as desired and then just invoke a single save operation.\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAInstance instance = MOCA.getInstance();\\ninstance.setProperty(\\\"favorite-color\\\", \\\"red\\\");\\ninstance.setProperty(\\\"current-plan\\\", \\\"starter\\\");\\ninstance.save(new MOCACallback<MOCAInstance>() {\\n  @Override\\n  public void success(MOCAInstance responseType) {\\n    Log.i(\\\"moca-sample\\\", \\\"All ok!\\\");\\n  }\\n\\n  @Override\\n  public void failure(MOCAException error) {\\n    Log.e(\\\"moca-sample\\\",\\\"Something went wrong!\\\" );\\n  }\\n});\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","updates":[],"order":8,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T15:32:55.056Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Instance API Android


- The app `Instance object` is a local representation of an app instance downloaded and installed in a user device. It contains the anonymous user profile. - The instance object is **automatically managed** by MOCA. [block:code] { "codes": [ { "code": "MOCAInstance instance = MOCA.getInstance();", "language": "java" } ] } [/block] - The instance object holds a **collection of properties**. Property-value pairs can be set and retrieved and are persisted between app sessions. [block:code] { "codes": [ { "code": "/**\n * Sets the value for the given property name.\n * \n * @param value Value to be set. It must belong to one of the accepted classes.\n * @param key Property name.\n */\n public void setProperty(String key, Object value);\n\n /**\n * Gets the value for the given property.\n *\n * @param key Property name.\n * @return Value associated with the key or <code>null</code> if none.\n */\n public Object getProperty(String key);\n ", "language": "java" } ] } [/block] - Each instance object is persisted both locally and in the cloud. The instance is automatically uploaded to the cloud each time the app starts. - The instance can be saved manually to the cloud. All saves are asynchronous. - It is recommended to perform as many sets as desired and then just invoke a single save operation. [block:code] { "codes": [ { "code": "MOCAInstance instance = MOCA.getInstance();\ninstance.setProperty(\"favorite-color\", \"red\");\ninstance.setProperty(\"current-plan\", \"starter\");\ninstance.save(new MOCACallback<MOCAInstance>() {\n @Override\n public void success(MOCAInstance responseType) {\n Log.i(\"moca-sample\", \"All ok!\");\n }\n\n @Override\n public void failure(MOCAException error) {\n Log.e(\"moca-sample\",\"Something went wrong!\" );\n }\n});", "language": "java" } ] } [/block]
- The app `Instance object` is a local representation of an app instance downloaded and installed in a user device. It contains the anonymous user profile. - The instance object is **automatically managed** by MOCA. [block:code] { "codes": [ { "code": "MOCAInstance instance = MOCA.getInstance();", "language": "java" } ] } [/block] - The instance object holds a **collection of properties**. Property-value pairs can be set and retrieved and are persisted between app sessions. [block:code] { "codes": [ { "code": "/**\n * Sets the value for the given property name.\n * \n * @param value Value to be set. It must belong to one of the accepted classes.\n * @param key Property name.\n */\n public void setProperty(String key, Object value);\n\n /**\n * Gets the value for the given property.\n *\n * @param key Property name.\n * @return Value associated with the key or <code>null</code> if none.\n */\n public Object getProperty(String key);\n ", "language": "java" } ] } [/block] - Each instance object is persisted both locally and in the cloud. The instance is automatically uploaded to the cloud each time the app starts. - The instance can be saved manually to the cloud. All saves are asynchronous. - It is recommended to perform as many sets as desired and then just invoke a single save operation. [block:code] { "codes": [ { "code": "MOCAInstance instance = MOCA.getInstance();\ninstance.setProperty(\"favorite-color\", \"red\");\ninstance.setProperty(\"current-plan\", \"starter\");\ninstance.save(new MOCACallback<MOCAInstance>() {\n @Override\n public void success(MOCAInstance responseType) {\n Log.i(\"moca-sample\", \"All ok!\");\n }\n\n @Override\n public void failure(MOCAException error) {\n Log.e(\"moca-sample\",\"Something went wrong!\" );\n }\n});", "language": "java" } ] } [/block]
{"_id":"5fe0c1d218e861016ecf97c3","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","params":[],"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]}},"next":{"description":"","pages":[]},"title":"User API Android","type":"basic","slug":"user-api-android","excerpt":"","body":"- The app **User object** manages information about current application user.\n- This object is **optional**, and it is used when the app needs to authenticate the user. \n- The authentication provides data about user’s identity: a unique user ID or similar. \n- The user login and logout calls are managed by the app. \u000b\n\n - To access existing User object, use currentUser property: \u000b\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//If no login has been done\\nMOCAUser user = MOCA.getInstance().login(applicationUserId);\\n\\n//User is already logged in\\nMOCAUser user = MOCA.getInstance().getUser();\\n        \",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"User will stay \\\"Logged in\\\" in MOCA SDK until you explicitly call the logout method\",\n  \"title\": \"User will persist across restarts\"\n}\n[/block]\n- To logout a user, call:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"user.logout()\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n- The user object holds a collection of properties. Property-value pairs can be set and retrieved.\n- Each user object is persisted both locally and in the cloud. \n- It is recommended to perform as many sets as desired and then \njust invoke a single save operation to persist them to the MOCA cloud.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"user.setProperty(\\\"is_tester\\\", true);\\nuser.setProperty(\\\"gender\\\", \\\"male\\\");\\nuser.setProperty(\\\"height\\\", 175.2);\\nuser.setProperty(\\\"dateOfBirth\\\", 0);\\nuser.save(new MOCACallback<MOCAUser>() {\\n  @Override\\n  public void success(MOCAUser user) {\\n\\n  }\\n\\n  @Override\\n  public void failure(MOCAException error) {\\n\\n  }\\n});\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","updates":[],"order":9,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T15:40:02.712Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

User API Android


- The app **User object** manages information about current application user. - This object is **optional**, and it is used when the app needs to authenticate the user. - The authentication provides data about user’s identity: a unique user ID or similar. - The user login and logout calls are managed by the app. - To access existing User object, use currentUser property: [block:code] { "codes": [ { "code": "//If no login has been done\nMOCAUser user = MOCA.getInstance().login(applicationUserId);\n\n//User is already logged in\nMOCAUser user = MOCA.getInstance().getUser();\n ", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "body": "User will stay \"Logged in\" in MOCA SDK until you explicitly call the logout method", "title": "User will persist across restarts" } [/block] - To logout a user, call: [block:code] { "codes": [ { "code": "user.logout()", "language": "java" } ] } [/block] - The user object holds a collection of properties. Property-value pairs can be set and retrieved. - Each user object is persisted both locally and in the cloud. - It is recommended to perform as many sets as desired and then just invoke a single save operation to persist them to the MOCA cloud. [block:code] { "codes": [ { "code": "user.setProperty(\"is_tester\", true);\nuser.setProperty(\"gender\", \"male\");\nuser.setProperty(\"height\", 175.2);\nuser.setProperty(\"dateOfBirth\", 0);\nuser.save(new MOCACallback<MOCAUser>() {\n @Override\n public void success(MOCAUser user) {\n\n }\n\n @Override\n public void failure(MOCAException error) {\n\n }\n});", "language": "java" } ] } [/block]
- The app **User object** manages information about current application user. - This object is **optional**, and it is used when the app needs to authenticate the user. - The authentication provides data about user’s identity: a unique user ID or similar. - The user login and logout calls are managed by the app. - To access existing User object, use currentUser property: [block:code] { "codes": [ { "code": "//If no login has been done\nMOCAUser user = MOCA.getInstance().login(applicationUserId);\n\n//User is already logged in\nMOCAUser user = MOCA.getInstance().getUser();\n ", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "body": "User will stay \"Logged in\" in MOCA SDK until you explicitly call the logout method", "title": "User will persist across restarts" } [/block] - To logout a user, call: [block:code] { "codes": [ { "code": "user.logout()", "language": "java" } ] } [/block] - The user object holds a collection of properties. Property-value pairs can be set and retrieved. - Each user object is persisted both locally and in the cloud. - It is recommended to perform as many sets as desired and then just invoke a single save operation to persist them to the MOCA cloud. [block:code] { "codes": [ { "code": "user.setProperty(\"is_tester\", true);\nuser.setProperty(\"gender\", \"male\");\nuser.setProperty(\"height\", 175.2);\nuser.setProperty(\"dateOfBirth\", 0);\nuser.save(new MOCACallback<MOCAUser>() {\n @Override\n public void success(MOCAUser user) {\n\n }\n\n @Override\n public void failure(MOCAException error) {\n\n }\n});", "language": "java" } ] } [/block]
{"_id":"5f998577fb81e800451c031a","next":{"pages":[],"description":""},"order":10,"sync_unique":"","body":"- To sense user interests, MOCA uses *Tags*.\n- Tags are small items of information with well defined semantics. \n- Each tag is associated with a ***counter***. The counter is used to track how many times the user was tagged or to sum points associated with the tag. \n- Tags are defined in MOCA Console or by the app.\n- For example: `Restaurant` `Video Store` `Woman` `Parking` `Gym`\n- Tags can be attached to specific locations by using beacons or programmatically by API.\n- Tag counters are used to rank the tags.\n\n\n-A single Tag is modeled as follows:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n * MOCATag represents a category of interest. Sample tags include \\\"books\\\",\\n * \\\"video\\\", \\\"music\\\", \\\"food\\\", or\\n */\\npublic interface MOCATag {\\n    /**\\n     * Get tag's name.\\n     *\\n     * @return tag name\\n     */\\n    public String getName();\\n\\n    /**\\n     * Get tag's weight.\\n     *\\n     * @return weight value\\n     */\\n    public double getValue();\\n\\n    /**\\n     * Get date tag was created.\\n     * @return UTC timestamp\\n     */\\n    public long getCreatedAt();\\n\\n    /**\\n     * Get last modification date.\\n     * @return UTC timestamp\\n     */\\n    public long getModifiedAt ();\\n\\n}\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nMOCA provides the following methods to manipulate Tags.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n\\t  /**\\n\\t   * Retrieves a collection of tags for this instance.\\n\\t   */\\n\\t  public Set<MOCATag> getTags();\\n\\n    /**\\n     * Add a tag to this instance and increment its value by 1.\\n     */\\n    public void addTag (String tagName);\\n\\n    /**\\n     * Add a tag with a given value to this instance.\\n     * @value - update expression with syntax [=|+|-] <double> value.\\n     * For example \\\"+1\\\" increments the tag value by 1.\\n     * For example \\\"-2\\\" decrements the tag value by 2.\\n     * For example \\\"3\\\" or \\\"=3\\\" assign value of 3 to the tag's value.\\n     */\\n    public void addTag (String tagName, String value);\\n\\n    /**\\n     * Checks if this instance contains a specific tag.\\n     * @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\\n     */\\n    public boolean containsTag (String tagName);\\n\\n    /**\\n     * Retrieves a value of a specific tag associated with this instance.\\n     * @return tag value or <code>nil</code> if the tag doest not exist.\\n     */\\n    public Double getTagValue (String tagName);\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","createdAt":"2015-07-17T17:23:13.913Z","link_url":"","parentDoc":null,"title":"Tag API","type":"basic","updates":[],"__v":0,"category":"5f998576fb81e800451c02f5","isReference":false,"link_external":false,"githubsync":"","hidden":false,"project":"559a61d2dbcfd20d00710b39","slug":"tag-api","user":"559a618bdbcfd20d00710b38","version":"5f998577fb81e800451c032f","api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Tag API


- To sense user interests, MOCA uses *Tags*. - Tags are small items of information with well defined semantics. - Each tag is associated with a ***counter***. The counter is used to track how many times the user was tagged or to sum points associated with the tag. - Tags are defined in MOCA Console or by the app. - For example: `Restaurant` `Video Store` `Woman` `Parking` `Gym` - Tags can be attached to specific locations by using beacons or programmatically by API. - Tag counters are used to rank the tags. -A single Tag is modeled as follows: [block:code] { "codes": [ { "code": "/**\n * MOCATag represents a category of interest. Sample tags include \"books\",\n * \"video\", \"music\", \"food\", or\n */\npublic interface MOCATag {\n /**\n * Get tag's name.\n *\n * @return tag name\n */\n public String getName();\n\n /**\n * Get tag's weight.\n *\n * @return weight value\n */\n public double getValue();\n\n /**\n * Get date tag was created.\n * @return UTC timestamp\n */\n public long getCreatedAt();\n\n /**\n * Get last modification date.\n * @return UTC timestamp\n */\n public long getModifiedAt ();\n\n}\n", "language": "java" } ] } [/block] MOCA provides the following methods to manipulate Tags. [block:code] { "codes": [ { "code": "\n\t /**\n\t * Retrieves a collection of tags for this instance.\n\t */\n\t public Set<MOCATag> getTags();\n\n /**\n * Add a tag to this instance and increment its value by 1.\n */\n public void addTag (String tagName);\n\n /**\n * Add a tag with a given value to this instance.\n * @value - update expression with syntax [=|+|-] <double> value.\n * For example \"+1\" increments the tag value by 1.\n * For example \"-2\" decrements the tag value by 2.\n * For example \"3\" or \"=3\" assign value of 3 to the tag's value.\n */\n public void addTag (String tagName, String value);\n\n /**\n * Checks if this instance contains a specific tag.\n * @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\n */\n public boolean containsTag (String tagName);\n\n /**\n * Retrieves a value of a specific tag associated with this instance.\n * @return tag value or <code>nil</code> if the tag doest not exist.\n */\n public Double getTagValue (String tagName);\n", "language": "java" } ] } [/block]
- To sense user interests, MOCA uses *Tags*. - Tags are small items of information with well defined semantics. - Each tag is associated with a ***counter***. The counter is used to track how many times the user was tagged or to sum points associated with the tag. - Tags are defined in MOCA Console or by the app. - For example: `Restaurant` `Video Store` `Woman` `Parking` `Gym` - Tags can be attached to specific locations by using beacons or programmatically by API. - Tag counters are used to rank the tags. -A single Tag is modeled as follows: [block:code] { "codes": [ { "code": "/**\n * MOCATag represents a category of interest. Sample tags include \"books\",\n * \"video\", \"music\", \"food\", or\n */\npublic interface MOCATag {\n /**\n * Get tag's name.\n *\n * @return tag name\n */\n public String getName();\n\n /**\n * Get tag's weight.\n *\n * @return weight value\n */\n public double getValue();\n\n /**\n * Get date tag was created.\n * @return UTC timestamp\n */\n public long getCreatedAt();\n\n /**\n * Get last modification date.\n * @return UTC timestamp\n */\n public long getModifiedAt ();\n\n}\n", "language": "java" } ] } [/block] MOCA provides the following methods to manipulate Tags. [block:code] { "codes": [ { "code": "\n\t /**\n\t * Retrieves a collection of tags for this instance.\n\t */\n\t public Set<MOCATag> getTags();\n\n /**\n * Add a tag to this instance and increment its value by 1.\n */\n public void addTag (String tagName);\n\n /**\n * Add a tag with a given value to this instance.\n * @value - update expression with syntax [=|+|-] <double> value.\n * For example \"+1\" increments the tag value by 1.\n * For example \"-2\" decrements the tag value by 2.\n * For example \"3\" or \"=3\" assign value of 3 to the tag's value.\n */\n public void addTag (String tagName, String value);\n\n /**\n * Checks if this instance contains a specific tag.\n * @return <code>YES</code> if the instance contains a tag, or <code>NO</code> otherwise.\n */\n public boolean containsTag (String tagName);\n\n /**\n * Retrieves a value of a specific tag associated with this instance.\n * @return tag value or <code>nil</code> if the tag doest not exist.\n */\n public Double getTagValue (String tagName);\n", "language": "java" } ] } [/block]
{"_id":"5fe0c2ca5e0cd402283aa9ad","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","params":[]},"next":{"description":"","pages":[]},"title":"Screen API Android","type":"basic","slug":"screen-api-android","excerpt":"","body":"MOCA SDK tracks automatically fragments/views of your App: this is great for tracking the screens viewed, where users dropped and how long they remained on each screen. In order to make the marketer's life easy we also offer a way to manually add a pretty name to each screen. You'll find an example below:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    /**\\n     * Sets the name of the current Activity. This information is used for \\\"Screen Analytics\\\"\\n     * within MOCA.\\n     *\\n     * @param activity   the activity usage to be tracked\\n     * @param screenName activity name\\n     */\\n    public static void currentScreen(@NonNull Activity activity, @NonNull String screenName)\",\n      \"language\": \"objectivec\",\n      \"name\": null\n    }\n  ]\n}\n[/block]\nExample, from an activity:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" MOCA.currentScreen(this, \\\"ticket_view\\\");\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"Ensure screen names are normalized between iOS and Android. Otherwise creating campaigns using these events won't be consistent between platforms.\",\n  \"title\": \"Check the name\"\n}\n[/block]\nIf your applications uses fragments, call the `currentScreen` on each fragment change. E.g:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    private void replaceFragment(final Fragment fragment, final String title) {\\n        final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();\\n        fragmentTransaction.replace(R.id.frame, fragment);\\n        fragmentTransaction.commit();\\n        final ActionBar actionBar = getSupportActionBar();\\n        if (actionBar != null) {\\n            getSupportActionBar().setTitle(title);\\n        }\\n      //--------------------------------\\n        MOCA.currentScreen(this, title);\\n      //--------------------------------\\n    }\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","updates":[],"order":11,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T15:44:10.208Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Screen API Android


MOCA SDK tracks automatically fragments/views of your App: this is great for tracking the screens viewed, where users dropped and how long they remained on each screen. In order to make the marketer's life easy we also offer a way to manually add a pretty name to each screen. You'll find an example below: [block:code] { "codes": [ { "code": " /**\n * Sets the name of the current Activity. This information is used for \"Screen Analytics\"\n * within MOCA.\n *\n * @param activity the activity usage to be tracked\n * @param screenName activity name\n */\n public static void currentScreen(@NonNull Activity activity, @NonNull String screenName)", "language": "objectivec", "name": null } ] } [/block] Example, from an activity: [block:code] { "codes": [ { "code": " MOCA.currentScreen(this, \"ticket_view\");", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "body": "Ensure screen names are normalized between iOS and Android. Otherwise creating campaigns using these events won't be consistent between platforms.", "title": "Check the name" } [/block] If your applications uses fragments, call the `currentScreen` on each fragment change. E.g: [block:code] { "codes": [ { "code": " private void replaceFragment(final Fragment fragment, final String title) {\n final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();\n fragmentTransaction.replace(R.id.frame, fragment);\n fragmentTransaction.commit();\n final ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n getSupportActionBar().setTitle(title);\n }\n //--------------------------------\n MOCA.currentScreen(this, title);\n //--------------------------------\n }", "language": "java" } ] } [/block]
MOCA SDK tracks automatically fragments/views of your App: this is great for tracking the screens viewed, where users dropped and how long they remained on each screen. In order to make the marketer's life easy we also offer a way to manually add a pretty name to each screen. You'll find an example below: [block:code] { "codes": [ { "code": " /**\n * Sets the name of the current Activity. This information is used for \"Screen Analytics\"\n * within MOCA.\n *\n * @param activity the activity usage to be tracked\n * @param screenName activity name\n */\n public static void currentScreen(@NonNull Activity activity, @NonNull String screenName)", "language": "objectivec", "name": null } ] } [/block] Example, from an activity: [block:code] { "codes": [ { "code": " MOCA.currentScreen(this, \"ticket_view\");", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "body": "Ensure screen names are normalized between iOS and Android. Otherwise creating campaigns using these events won't be consistent between platforms.", "title": "Check the name" } [/block] If your applications uses fragments, call the `currentScreen` on each fragment change. E.g: [block:code] { "codes": [ { "code": " private void replaceFragment(final Fragment fragment, final String title) {\n final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();\n fragmentTransaction.replace(R.id.frame, fragment);\n fragmentTransaction.commit();\n final ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n getSupportActionBar().setTitle(title);\n }\n //--------------------------------\n MOCA.currentScreen(this, title);\n //--------------------------------\n }", "language": "java" } ] } [/block]
{"_id":"5fe0c3ff56af15003ca3034e","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Location Events Listener Android","type":"basic","slug":"location-events-listener-android","excerpt":"","body":"Your application can listen to location `enter` or `exit` events. \nBefore deep diving into the available methods, lets briefly see what kind of location objects does MOCA define:\n[block:api-header]\n{\n  \"title\": \"Location related classes\"\n}\n[/block]\n`MOCABeacon`: A bluetooth beacon.\n`MOCAZone`: A Group of `MOCABeacon`.\n`MOCAPlace`: A region defined by a geofence. It could contain multiple `MOCAZone`\n`MOCARegionGroup`: Flexible class that can contain multiple `MOCABeacon`, `MOCAZone ` or `MOCAPlace `.\n\nAll classes above inherit from `MOCARegion`\n[block:api-header]\n{\n  \"title\": \"Available methods\"\n}\n[/block]\nLocation event listeners are segregated in several interfaces so you can pick what works best for your use case.\n\nListening to _all_ region type events: \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"interface RegionEventsObserver extends IObserverHandler.ObserverId {\\n  default void onEnterRegion(MOCARegion region){}\\n  default void onExitRegion(MOCARegion region){};\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nIf you want to listen only a specific type of regions. Implement the appropriate protocol.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"interface PlaceEventsObserver extends RegionEventsObserver {\\n  void onEnterPlace(MOCAPlace region);\\n  void onExitPlace(MOCAPlace region);\\n}\\n\\ninterface ZoneEventsObserver extends RegionEventsObserver {\\n  void onEnterZone(MOCAZone region);\\n  void onExitZone(MOCAZone region);\\n}\\n\\ninterface BeaconEventsObserver extends RegionEventsObserver {\\n  void onEnterBeacon(MOCABeacon region);\\n  void onExitBeacon(MOCABeacon region);\\n}\\n\\ninterface RegionGroupEventsObserver extends RegionEventsObserver {\\n  void onEnterRegionGroup(MOCARegionGroup region);\\n  void onExitRegionGroup(MOCARegionGroup region);\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nInstall an observer by calling\n\n`MOCA.addRegionObserver(observer);`","updates":[],"order":12,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T15:49:19.116Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Location Events Listener Android


Your application can listen to location `enter` or `exit` events. Before deep diving into the available methods, lets briefly see what kind of location objects does MOCA define: [block:api-header] { "title": "Location related classes" } [/block] `MOCABeacon`: A bluetooth beacon. `MOCAZone`: A Group of `MOCABeacon`. `MOCAPlace`: A region defined by a geofence. It could contain multiple `MOCAZone` `MOCARegionGroup`: Flexible class that can contain multiple `MOCABeacon`, `MOCAZone ` or `MOCAPlace `. All classes above inherit from `MOCARegion` [block:api-header] { "title": "Available methods" } [/block] Location event listeners are segregated in several interfaces so you can pick what works best for your use case. Listening to _all_ region type events: [block:code] { "codes": [ { "code": "interface RegionEventsObserver extends IObserverHandler.ObserverId {\n default void onEnterRegion(MOCARegion region){}\n default void onExitRegion(MOCARegion region){};\n}", "language": "java" } ] } [/block] If you want to listen only a specific type of regions. Implement the appropriate protocol. [block:code] { "codes": [ { "code": "interface PlaceEventsObserver extends RegionEventsObserver {\n void onEnterPlace(MOCAPlace region);\n void onExitPlace(MOCAPlace region);\n}\n\ninterface ZoneEventsObserver extends RegionEventsObserver {\n void onEnterZone(MOCAZone region);\n void onExitZone(MOCAZone region);\n}\n\ninterface BeaconEventsObserver extends RegionEventsObserver {\n void onEnterBeacon(MOCABeacon region);\n void onExitBeacon(MOCABeacon region);\n}\n\ninterface RegionGroupEventsObserver extends RegionEventsObserver {\n void onEnterRegionGroup(MOCARegionGroup region);\n void onExitRegionGroup(MOCARegionGroup region);\n}", "language": "java" } ] } [/block] Install an observer by calling `MOCA.addRegionObserver(observer);`
Your application can listen to location `enter` or `exit` events. Before deep diving into the available methods, lets briefly see what kind of location objects does MOCA define: [block:api-header] { "title": "Location related classes" } [/block] `MOCABeacon`: A bluetooth beacon. `MOCAZone`: A Group of `MOCABeacon`. `MOCAPlace`: A region defined by a geofence. It could contain multiple `MOCAZone` `MOCARegionGroup`: Flexible class that can contain multiple `MOCABeacon`, `MOCAZone ` or `MOCAPlace `. All classes above inherit from `MOCARegion` [block:api-header] { "title": "Available methods" } [/block] Location event listeners are segregated in several interfaces so you can pick what works best for your use case. Listening to _all_ region type events: [block:code] { "codes": [ { "code": "interface RegionEventsObserver extends IObserverHandler.ObserverId {\n default void onEnterRegion(MOCARegion region){}\n default void onExitRegion(MOCARegion region){};\n}", "language": "java" } ] } [/block] If you want to listen only a specific type of regions. Implement the appropriate protocol. [block:code] { "codes": [ { "code": "interface PlaceEventsObserver extends RegionEventsObserver {\n void onEnterPlace(MOCAPlace region);\n void onExitPlace(MOCAPlace region);\n}\n\ninterface ZoneEventsObserver extends RegionEventsObserver {\n void onEnterZone(MOCAZone region);\n void onExitZone(MOCAZone region);\n}\n\ninterface BeaconEventsObserver extends RegionEventsObserver {\n void onEnterBeacon(MOCABeacon region);\n void onExitBeacon(MOCABeacon region);\n}\n\ninterface RegionGroupEventsObserver extends RegionEventsObserver {\n void onEnterRegionGroup(MOCARegionGroup region);\n void onExitRegionGroup(MOCARegionGroup region);\n}", "language": "java" } ] } [/block] Install an observer by calling `MOCA.addRegionObserver(observer);`
{"_id":"5f998577fb81e800451c031b","slug":"event-api-1","version":"5f998577fb81e800451c032f","__v":0,"createdAt":"2015-07-17T17:28:02.199Z","hidden":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","type":"basic","updates":[],"user":"559a618bdbcfd20d00710b38","body":"To track custom events in your app, use the following API:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"public class MOCA {\\n  /**\\n   * Tracks an event represented by an action verb \\n   *\\n   * @param verb Action verb. (E.g. Buy, View, Search, etc.).\\n   *\\n   * @return <code>true</code> in case of success, <code>false</code> in case of error.\\n   */\\n   public static boolean track (final String verb);\\n\\n   /**\\n    * Track event helper methods. \\n    */\\n    public static boolean track (final String verb, long value);\\n    public static boolean track (final String verb, final String item);\\n    public static boolean track (final String verb, final String item, final long value);\\n    public static boolean track (final String verb, final String category, final String item);\\n    public static boolean track (final String verb, final String category, final String item, final long value);\\n    public static boolean track (final String verb, final Map<String, Object> attrs);\\n}\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","category":"5f998576fb81e800451c02f5","excerpt":"","order":13,"isReference":false,"parentDoc":null,"sync_unique":"","api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"githubsync":"","link_external":false,"next":{"pages":[],"description":""},"title":"Event API","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Event API


To track custom events in your app, use the following API: [block:code] { "codes": [ { "code": "public class MOCA {\n /**\n * Tracks an event represented by an action verb \n *\n * @param verb Action verb. (E.g. Buy, View, Search, etc.).\n *\n * @return <code>true</code> in case of success, <code>false</code> in case of error.\n */\n public static boolean track (final String verb);\n\n /**\n * Track event helper methods. \n */\n public static boolean track (final String verb, long value);\n public static boolean track (final String verb, final String item);\n public static boolean track (final String verb, final String item, final long value);\n public static boolean track (final String verb, final String category, final String item);\n public static boolean track (final String verb, final String category, final String item, final long value);\n public static boolean track (final String verb, final Map<String, Object> attrs);\n}\n", "language": "java" } ] } [/block]
To track custom events in your app, use the following API: [block:code] { "codes": [ { "code": "public class MOCA {\n /**\n * Tracks an event represented by an action verb \n *\n * @param verb Action verb. (E.g. Buy, View, Search, etc.).\n *\n * @return <code>true</code> in case of success, <code>false</code> in case of error.\n */\n public static boolean track (final String verb);\n\n /**\n * Track event helper methods. \n */\n public static boolean track (final String verb, long value);\n public static boolean track (final String verb, final String item);\n public static boolean track (final String verb, final String item, final long value);\n public static boolean track (final String verb, final String category, final String item);\n public static boolean track (final String verb, final String category, final String item, final long value);\n public static boolean track (final String verb, final Map<String, Object> attrs);\n}\n", "language": "java" } ] } [/block]
{"_id":"5fe0c4aa144772007c3b21b4","metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"params":[]},"next":{"description":"","pages":[]},"title":"Custom experiences handling Android","type":"basic","slug":"custom-experiences-handling-android","excerpt":"","body":"Optionally, you can handle \"custom\" MOCA Experiences yourself. The SDK will evaluate the campaign and experience settings, and let you know when the events happened so you can react accordingly.\n\nRegister your handler by calling \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setCustomActionHandler(this); \",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nWhere `this` implements the `Action.CustomActionHandler` protocol.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"interface CustomActionHandler {\\n  boolean performCustomAction(Experience sender, String customAttribute);\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","updates":[],"order":14,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"createdAt":"2020-12-21T15:52:10.041Z","user":"559a618bdbcfd20d00710b38","category":"5f998576fb81e800451c02f5","version":"5f998577fb81e800451c032f","project":"559a61d2dbcfd20d00710b39","__v":0,"parentDoc":null,"childrenPages":[]}

Custom experiences handling Android


Optionally, you can handle "custom" MOCA Experiences yourself. The SDK will evaluate the campaign and experience settings, and let you know when the events happened so you can react accordingly. Register your handler by calling [block:code] { "codes": [ { "code": "MOCA.setCustomActionHandler(this); ", "language": "java" } ] } [/block] Where `this` implements the `Action.CustomActionHandler` protocol. [block:code] { "codes": [ { "code": "interface CustomActionHandler {\n boolean performCustomAction(Experience sender, String customAttribute);\n}", "language": "java" } ] } [/block]
Optionally, you can handle "custom" MOCA Experiences yourself. The SDK will evaluate the campaign and experience settings, and let you know when the events happened so you can react accordingly. Register your handler by calling [block:code] { "codes": [ { "code": "MOCA.setCustomActionHandler(this); ", "language": "java" } ] } [/block] Where `this` implements the `Action.CustomActionHandler` protocol. [block:code] { "codes": [ { "code": "interface CustomActionHandler {\n boolean performCustomAction(Experience sender, String customAttribute);\n}", "language": "java" } ] } [/block]
{"_id":"5f998577fb81e800451c0311","__v":0,"isReference":false,"title":"Cordova / PhoneGap - Installation","updates":[],"body":"This plugin supports **PhoneGap/Cordova** apps running on iOS and Android.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Version requirements\"\n}\n[/block]\nThis plugin is meant to work with Cordova 3.4.0+ and the latest versions of the MOCA SDK libraries.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Installation\"\n}\n[/block]\nAutomatic installation using PhoneGap/Cordova CLI (iOS and Android)\n\n1. For iOS, make sure you update your iOS project to Cordova iOS version 3.4.1 or newer before installing this plugin.\n\n  ````\n    cordova platform add ios\n  ````\n  \n2. For Android, make sure the Android SDK is up to date. Google Play Services 7.5+ is required (8.5+ for Remote Push Notifications through Google Cloud Messaging).\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Android Cordova version\",\n  \"body\": \"Latest plugin version requieres Cordova Android 8.0.0\"\n}\n[/block]\n  ````\n    cordova platform add [email protected]\n  ````\n   \n3. Install this plugin using PhoneGap/Cordova cli:\n\n   ````\n    cordova plugin add https://github.com/mocaplatform/moca-phonegap-sdk.git\n   ````\n   \n4. Modify the config.xml directory to contain (replacing with your configuration settings):\nThe `targetSdkVersion` value should match the target of your project.\n   \n   ````\n   <!-- MOCA SDK credentials -->\n   <preference name=\"moca_app_key\" value=\"YOUR_APP_KEY\" />\n   <preference name=\"moca_app_secret\" value=\"YOUR-APP-SECRET\" />\n   <preference name=\"gcm_sender\" value=\"\\ YOUR_GCM_SENDER\" />\n    <platform name=\"android\">\n    ...\n        <preference name=\"android-minSdkVersion\" value=\"19\" />\n        <preference name=\"android-targetSdkVersion\" value=\"23\" />\n    ...\n    </platform>\n   ````\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"NOTE\",\n  \"body\": \"There is a `space` after the backslash `\\\\` in the `\\\"gcm_sender\\\"` field. **Do not delete the space character**, otherwise key won't be read correctly.\\n\\nvalue=\\\"\\\\\\\\` `YOUR_GCM_SENDER\\\"\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Android - Caveats\"\n}\n[/block]\n##Permissions in Android 6+\n\nStarting with Android Marshmallow (6.0), some permissions must be requested at runtime, rather than at install time. For the MOCA SDK, this means that you need to ask to the user for the 'ACCESS_FINE_LOCATION' permission when the App is executed for the first time. Otherwise, neither beacons nor geofences will be detected.\n\nYou can use a 3rd party plugin to do this, such as [this one](https://www.npmjs.com/package/cordova-plugin-android-permissions).\n\nAfter the permission is granted, you can manually start the affected services by calling:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setGeoTrackingEnabled(true, callback);\\nMOCA.setProximityEnabled(true, callback);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nBelow you will find a working code sample of this integration, notice the `requestMocaPermissions` and `startProximityServices` methods. And how `requestMocaPermissions` is called in `onDeviceReady`.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var app = {\\n    // Application Constructor\\n    initialize: function() {\\n        this.bindEvents();\\n    },\\n    // Bind Event Listeners\\n    //\\n    // Bind any events that are required on startup. Common events are:\\n    // 'load', 'deviceready', 'offline', and 'online'.\\n    bindEvents: function() {\\n        document.addEventListener('deviceready', this.onDeviceReady, false);\\n    },\\n    // deviceready Event Handler\\n    //\\n    // The scope of 'this' is the event. In order to call the 'receivedEvent'\\n    // function, we must explicitly call 'app.receivedEvent(...);'\\n    onDeviceReady: function() {\\n        app.receivedEvent('deviceready');\\n      \\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\\n      \\n        /*Request permissions at RunTime*/\\n        app.requestMocaPermissions();\\n    },\\n    requestMocaPermissions: function(){\\n        var permissions = cordova.plugins.permissions;\\n        var onError = function(e) {\\n            console.error(error, e);\\n        };\\n        var onRequestPermissionResult = function(permStatus){\\n            permStatus.hasPermission? app.startProximityServices(): console.warn(\\\"Location Permission denied\\\");  \\n        };\\n        var onPermissionStatus = function(permStatus) {\\n            if(!permStatus.hasPermission){\\n                permissions.requestPermission(permissions.ACCESS_FINE_LOCATION, onRequestPermissionResult, onError);\\n            }\\n            else {\\n               app.startProximityServices();\\n            }\\n        };\\n        permissions.hasPermission(permissions.ACCESS_FINE_LOCATION, onPermissionStatus, onError);\\n    },\\n    startProximityServices: function() {\\n        MOCA.setProximityEnabled(true);\\n        MOCA.setGeoTrackingEnabled(true);\\n    },\\n  \\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\\n\\n    // Update DOM on a Received Event\\n    receivedEvent: function(id) {\\n        var parentElement = document.getElementById(id);\\n        var listeningElement = parentElement.querySelector('.listening');\\n        var receivedElement = parentElement.querySelector('.received');\\n\\n        listeningElement.setAttribute('style', 'display:none;');\\n        receivedElement.setAttribute('style', 'display:block;');\\n\\n        console.log('Received Event: ' + id);\\n    }\\n};\",\n      \"language\": \"javascript\",\n      \"name\": \"Permissions Sample\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"iOS - Caveats\"\n}\n[/block]\n##App Transport Security\n\nIn order to receive experiences served through non-secured connections, [please configure *App Transport Security* ](http://developer.mocaplatform.com/docs/moca-ios-sdk-configuration#section-app-transport-security) properly within the Xcode project,\n\n##Customizing text when requesting Location Permission\n\nYou may want to modify the message shown to the user when prompting for location permission. In order to do so, open the `YourAppName-Info.plist` file and edit the `NSLocationAlwaysUsageDescription` key.","createdAt":"2015-07-31T09:48:00.282Z","excerpt":"","hidden":false,"next":{"description":"","pages":[]},"slug":"moca-cordova-sdk-installation","sync_unique":"","githubsync":"","order":0,"type":"basic","version":"5f998577fb81e800451c032f","api":{"auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":""},"category":"5f998576fb81e800451c02f7","link_external":false,"link_url":"","parentDoc":null,"project":"559a61d2dbcfd20d00710b39","user":"559a618bdbcfd20d00710b38","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Cordova / PhoneGap - Installation


This plugin supports **PhoneGap/Cordova** apps running on iOS and Android. [block:api-header] { "type": "basic", "title": "Version requirements" } [/block] This plugin is meant to work with Cordova 3.4.0+ and the latest versions of the MOCA SDK libraries. [block:api-header] { "type": "basic", "title": "Installation" } [/block] Automatic installation using PhoneGap/Cordova CLI (iOS and Android) 1. For iOS, make sure you update your iOS project to Cordova iOS version 3.4.1 or newer before installing this plugin. ```` cordova platform add ios ```` 2. For Android, make sure the Android SDK is up to date. Google Play Services 7.5+ is required (8.5+ for Remote Push Notifications through Google Cloud Messaging). [block:callout] { "type": "warning", "title": "Android Cordova version", "body": "Latest plugin version requieres Cordova Android 8.0.0" } [/block] ```` cordova platform add an[email protected] ```` 3. Install this plugin using PhoneGap/Cordova cli: ```` cordova plugin add https://github.com/mocaplatform/moca-phonegap-sdk.git ```` 4. Modify the config.xml directory to contain (replacing with your configuration settings): The `targetSdkVersion` value should match the target of your project. ```` <!-- MOCA SDK credentials --> <preference name="moca_app_key" value="YOUR_APP_KEY" /> <preference name="moca_app_secret" value="YOUR-APP-SECRET" /> <preference name="gcm_sender" value="\ YOUR_GCM_SENDER" /> <platform name="android"> ... <preference name="android-minSdkVersion" value="19" /> <preference name="android-targetSdkVersion" value="23" /> ... </platform> ```` [block:callout] { "type": "danger", "title": "NOTE", "body": "There is a `space` after the backslash `\\` in the `\"gcm_sender\"` field. **Do not delete the space character**, otherwise key won't be read correctly.\n\nvalue=\"\\\\` `YOUR_GCM_SENDER\"" } [/block] [block:api-header] { "type": "basic", "title": "Android - Caveats" } [/block] ##Permissions in Android 6+ Starting with Android Marshmallow (6.0), some permissions must be requested at runtime, rather than at install time. For the MOCA SDK, this means that you need to ask to the user for the 'ACCESS_FINE_LOCATION' permission when the App is executed for the first time. Otherwise, neither beacons nor geofences will be detected. You can use a 3rd party plugin to do this, such as [this one](https://www.npmjs.com/package/cordova-plugin-android-permissions). After the permission is granted, you can manually start the affected services by calling: [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true, callback);\nMOCA.setProximityEnabled(true, callback);", "language": "javascript" } ] } [/block] Below you will find a working code sample of this integration, notice the `requestMocaPermissions` and `startProximityServices` methods. And how `requestMocaPermissions` is called in `onDeviceReady`. [block:code] { "codes": [ { "code": "var app = {\n // Application Constructor\n initialize: function() {\n this.bindEvents();\n },\n // Bind Event Listeners\n //\n // Bind any events that are required on startup. Common events are:\n // 'load', 'deviceready', 'offline', and 'online'.\n bindEvents: function() {\n document.addEventListener('deviceready', this.onDeviceReady, false);\n },\n // deviceready Event Handler\n //\n // The scope of 'this' is the event. In order to call the 'receivedEvent'\n // function, we must explicitly call 'app.receivedEvent(...);'\n onDeviceReady: function() {\n app.receivedEvent('deviceready');\n \n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n \n /*Request permissions at RunTime*/\n app.requestMocaPermissions();\n },\n requestMocaPermissions: function(){\n var permissions = cordova.plugins.permissions;\n var onError = function(e) {\n console.error(error, e);\n };\n var onRequestPermissionResult = function(permStatus){\n permStatus.hasPermission? app.startProximityServices(): console.warn(\"Location Permission denied\"); \n };\n var onPermissionStatus = function(permStatus) {\n if(!permStatus.hasPermission){\n permissions.requestPermission(permissions.ACCESS_FINE_LOCATION, onRequestPermissionResult, onError);\n }\n else {\n app.startProximityServices();\n }\n };\n permissions.hasPermission(permissions.ACCESS_FINE_LOCATION, onPermissionStatus, onError);\n },\n startProximityServices: function() {\n MOCA.setProximityEnabled(true);\n MOCA.setGeoTrackingEnabled(true);\n },\n \n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n // Update DOM on a Received Event\n receivedEvent: function(id) {\n var parentElement = document.getElementById(id);\n var listeningElement = parentElement.querySelector('.listening');\n var receivedElement = parentElement.querySelector('.received');\n\n listeningElement.setAttribute('style', 'display:none;');\n receivedElement.setAttribute('style', 'display:block;');\n\n console.log('Received Event: ' + id);\n }\n};", "language": "javascript", "name": "Permissions Sample" } ] } [/block] [block:api-header] { "type": "basic", "title": "iOS - Caveats" } [/block] ##App Transport Security In order to receive experiences served through non-secured connections, [please configure *App Transport Security* ](http://developer.mocaplatform.com/docs/moca-ios-sdk-configuration#section-app-transport-security) properly within the Xcode project, ##Customizing text when requesting Location Permission You may want to modify the message shown to the user when prompting for location permission. In order to do so, open the `YourAppName-Info.plist` file and edit the `NSLocationAlwaysUsageDescription` key.
This plugin supports **PhoneGap/Cordova** apps running on iOS and Android. [block:api-header] { "type": "basic", "title": "Version requirements" } [/block] This plugin is meant to work with Cordova 3.4.0+ and the latest versions of the MOCA SDK libraries. [block:api-header] { "type": "basic", "title": "Installation" } [/block] Automatic installation using PhoneGap/Cordova CLI (iOS and Android) 1. For iOS, make sure you update your iOS project to Cordova iOS version 3.4.1 or newer before installing this plugin. ```` cordova platform add ios ```` 2. For Android, make sure the Android SDK is up to date. Google Play Services 7.5+ is required (8.5+ for Remote Push Notifications through Google Cloud Messaging). [block:callout] { "type": "warning", "title": "Android Cordova version", "body": "Latest plugin version requieres Cordova Android 8.0.0" } [/block] ```` cordova platform add [email protected] ```` 3. Install this plugin using PhoneGap/Cordova cli: ```` cordova plugin add https://github.com/mocaplatform/moca-phonegap-sdk.git ```` 4. Modify the config.xml directory to contain (replacing with your configuration settings): The `targetSdkVersion` value should match the target of your project. ```` <!-- MOCA SDK credentials --> <preference name="moca_app_key" value="YOUR_APP_KEY" /> <preference name="moca_app_secret" value="YOUR-APP-SECRET" /> <preference name="gcm_sender" value="\ YOUR_GCM_SENDER" /> <platform name="android"> ... <preference name="android-minSdkVersion" value="19" /> <preference name="android-targetSdkVersion" value="23" /> ... </platform> ```` [block:callout] { "type": "danger", "title": "NOTE", "body": "There is a `space` after the backslash `\\` in the `\"gcm_sender\"` field. **Do not delete the space character**, otherwise key won't be read correctly.\n\nvalue=\"\\\\` `YOUR_GCM_SENDER\"" } [/block] [block:api-header] { "type": "basic", "title": "Android - Caveats" } [/block] ##Permissions in Android 6+ Starting with Android Marshmallow (6.0), some permissions must be requested at runtime, rather than at install time. For the MOCA SDK, this means that you need to ask to the user for the 'ACCESS_FINE_LOCATION' permission when the App is executed for the first time. Otherwise, neither beacons nor geofences will be detected. You can use a 3rd party plugin to do this, such as [this one](https://www.npmjs.com/package/cordova-plugin-android-permissions). After the permission is granted, you can manually start the affected services by calling: [block:code] { "codes": [ { "code": "MOCA.setGeoTrackingEnabled(true, callback);\nMOCA.setProximityEnabled(true, callback);", "language": "javascript" } ] } [/block] Below you will find a working code sample of this integration, notice the `requestMocaPermissions` and `startProximityServices` methods. And how `requestMocaPermissions` is called in `onDeviceReady`. [block:code] { "codes": [ { "code": "var app = {\n // Application Constructor\n initialize: function() {\n this.bindEvents();\n },\n // Bind Event Listeners\n //\n // Bind any events that are required on startup. Common events are:\n // 'load', 'deviceready', 'offline', and 'online'.\n bindEvents: function() {\n document.addEventListener('deviceready', this.onDeviceReady, false);\n },\n // deviceready Event Handler\n //\n // The scope of 'this' is the event. In order to call the 'receivedEvent'\n // function, we must explicitly call 'app.receivedEvent(...);'\n onDeviceReady: function() {\n app.receivedEvent('deviceready');\n \n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n \n /*Request permissions at RunTime*/\n app.requestMocaPermissions();\n },\n requestMocaPermissions: function(){\n var permissions = cordova.plugins.permissions;\n var onError = function(e) {\n console.error(error, e);\n };\n var onRequestPermissionResult = function(permStatus){\n permStatus.hasPermission? app.startProximityServices(): console.warn(\"Location Permission denied\"); \n };\n var onPermissionStatus = function(permStatus) {\n if(!permStatus.hasPermission){\n permissions.requestPermission(permissions.ACCESS_FINE_LOCATION, onRequestPermissionResult, onError);\n }\n else {\n app.startProximityServices();\n }\n };\n permissions.hasPermission(permissions.ACCESS_FINE_LOCATION, onPermissionStatus, onError);\n },\n startProximityServices: function() {\n MOCA.setProximityEnabled(true);\n MOCA.setGeoTrackingEnabled(true);\n },\n \n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n // Update DOM on a Received Event\n receivedEvent: function(id) {\n var parentElement = document.getElementById(id);\n var listeningElement = parentElement.querySelector('.listening');\n var receivedElement = parentElement.querySelector('.received');\n\n listeningElement.setAttribute('style', 'display:none;');\n receivedElement.setAttribute('style', 'display:block;');\n\n console.log('Received Event: ' + id);\n }\n};", "language": "javascript", "name": "Permissions Sample" } ] } [/block] [block:api-header] { "type": "basic", "title": "iOS - Caveats" } [/block] ##App Transport Security In order to receive experiences served through non-secured connections, [please configure *App Transport Security* ](http://developer.mocaplatform.com/docs/moca-ios-sdk-configuration#section-app-transport-security) properly within the Xcode project, ##Customizing text when requesting Location Permission You may want to modify the message shown to the user when prompting for location permission. In order to do so, open the `YourAppName-Info.plist` file and edit the `NSLocationAlwaysUsageDescription` key.
{"_id":"5f998577fb81e800451c0312","link_external":false,"title":"Configuration","hidden":false,"body":"The following are a set of required and optional configuration values you should set in your config.xml\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Key\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Default Value\",\n    \"h-3\": \"Description\",\n    \"h-4\": \"\",\n    \"0-0\": \"moca_app_key\",\n    \"0-1\": \"String (required)\",\n    \"0-3\": \"App key from MOCA Console\",\n    \"1-0\": \"moca_app_secret\",\n    \"1-1\": \"String (required)\",\n    \"1-3\": \"App secret from MOCA Console\",\n    \"2-0\": \"moca_log_level\",\n    \"2-1\": \"String\",\n    \"2-3\": \"MOCA SDK logging level:\\n* trace\\n* debug\\n* info\\n* warn\\n* error\",\n    \"2-2\": \"\\\"info\\\"\",\n    \"3-0\": \"moca_cache_disk_size_in_mb\",\n    \"3-1\": \"Integer\",\n    \"3-3\": \"Maximum local disk space available for SDK cache.\",\n    \"3-2\": \"100\",\n    \"4-0\": \"moca_automatic_push_setup_enabled\",\n    \"4-3\": \"If enabled, the SDK will automatically subscribe the app to push notification services and obtain push token.\",\n    \"4-1\": \"BOOL\",\n    \"4-2\": \"YES\",\n    \"5-0\": \"moca_proximity_service_enabled\",\n    \"5-1\": \"BOOL\",\n    \"5-2\": \"YES\",\n    \"5-3\": \"Enables or disables Bluetooth Beacon monitoring and ranging & geofence detection using *iOS Location Services*\",\n    \"6-0\": \"moca_geolocation_service_enabled\",\n    \"6-1\": \"BOOL\",\n    \"6-2\": \"YES\",\n    \"6-3\": \"Enables/disables tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\\n\\nWhen enabled (YES), user location will be tracked when the app is in foreground. Additionally, background tracking is controlled by BACKGROUND_LOCATION_ENABLED flag. This is the default.\\n\\nWhen disabled (NO), user location will not be tracked at all (neither in foreground nor on background). However, Bluetooth beacons and geofences will still be detected if this flag is set to NO.\",\n    \"7-0\": \"moca_background_location_enabled\",\n    \"7-1\": \"BOOL\",\n    \"7-2\": \"YES\",\n    \"7-3\": \"Enables/disables location tracking when the app is in background or suspended mode.\\n\\nThis flag has no effect if GEOLOCATION_SERVICE_ENABLED is set to NO.\\n\\nBy default background location tracking is enabled.\"\n  },\n  \"cols\": 4,\n  \"rows\": 8\n}\n[/block]\nFor further app permission configuration requirements please checkout [iOS'](http://developer.mocaplatform.com/docs/moca-ios-sdk-configuration#app-capabilities) and [Android's](http://developer.mocaplatform.com/docs/moca-android-sdk-configuration#setting-app-permissions) different needs.","category":"5f998576fb81e800451c02f7","createdAt":"2015-12-28T16:43:27.410Z","githubsync":"","link_url":"","order":1,"__v":0,"updates":[],"user":"55a61860249a40190051d941","project":"559a61d2dbcfd20d00710b39","next":{"pages":[],"description":""},"parentDoc":null,"version":"5f998577fb81e800451c032f","excerpt":"","isReference":false,"slug":"configuration","sync_unique":"","type":"basic","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]}},"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Configuration


The following are a set of required and optional configuration values you should set in your config.xml [block:parameters] { "data": { "h-0": "Key", "h-1": "Type", "h-2": "Default Value", "h-3": "Description", "h-4": "", "0-0": "moca_app_key", "0-1": "String (required)", "0-3": "App key from MOCA Console", "1-0": "moca_app_secret", "1-1": "String (required)", "1-3": "App secret from MOCA Console", "2-0": "moca_log_level", "2-1": "String", "2-3": "MOCA SDK logging level:\n* trace\n* debug\n* info\n* warn\n* error", "2-2": "\"info\"", "3-0": "moca_cache_disk_size_in_mb", "3-1": "Integer", "3-3": "Maximum local disk space available for SDK cache.", "3-2": "100", "4-0": "moca_automatic_push_setup_enabled", "4-3": "If enabled, the SDK will automatically subscribe the app to push notification services and obtain push token.", "4-1": "BOOL", "4-2": "YES", "5-0": "moca_proximity_service_enabled", "5-1": "BOOL", "5-2": "YES", "5-3": "Enables or disables Bluetooth Beacon monitoring and ranging & geofence detection using *iOS Location Services*", "6-0": "moca_geolocation_service_enabled", "6-1": "BOOL", "6-2": "YES", "6-3": "Enables/disables tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\n\nWhen enabled (YES), user location will be tracked when the app is in foreground. Additionally, background tracking is controlled by BACKGROUND_LOCATION_ENABLED flag. This is the default.\n\nWhen disabled (NO), user location will not be tracked at all (neither in foreground nor on background). However, Bluetooth beacons and geofences will still be detected if this flag is set to NO.", "7-0": "moca_background_location_enabled", "7-1": "BOOL", "7-2": "YES", "7-3": "Enables/disables location tracking when the app is in background or suspended mode.\n\nThis flag has no effect if GEOLOCATION_SERVICE_ENABLED is set to NO.\n\nBy default background location tracking is enabled." }, "cols": 4, "rows": 8 } [/block] For further app permission configuration requirements please checkout [iOS'](http://developer.mocaplatform.com/docs/moca-ios-sdk-configuration#app-capabilities) and [Android's](http://developer.mocaplatform.com/docs/moca-android-sdk-configuration#setting-app-permissions) different needs.
The following are a set of required and optional configuration values you should set in your config.xml [block:parameters] { "data": { "h-0": "Key", "h-1": "Type", "h-2": "Default Value", "h-3": "Description", "h-4": "", "0-0": "moca_app_key", "0-1": "String (required)", "0-3": "App key from MOCA Console", "1-0": "moca_app_secret", "1-1": "String (required)", "1-3": "App secret from MOCA Console", "2-0": "moca_log_level", "2-1": "String", "2-3": "MOCA SDK logging level:\n* trace\n* debug\n* info\n* warn\n* error", "2-2": "\"info\"", "3-0": "moca_cache_disk_size_in_mb", "3-1": "Integer", "3-3": "Maximum local disk space available for SDK cache.", "3-2": "100", "4-0": "moca_automatic_push_setup_enabled", "4-3": "If enabled, the SDK will automatically subscribe the app to push notification services and obtain push token.", "4-1": "BOOL", "4-2": "YES", "5-0": "moca_proximity_service_enabled", "5-1": "BOOL", "5-2": "YES", "5-3": "Enables or disables Bluetooth Beacon monitoring and ranging & geofence detection using *iOS Location Services*", "6-0": "moca_geolocation_service_enabled", "6-1": "BOOL", "6-2": "YES", "6-3": "Enables/disables tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\n\nWhen enabled (YES), user location will be tracked when the app is in foreground. Additionally, background tracking is controlled by BACKGROUND_LOCATION_ENABLED flag. This is the default.\n\nWhen disabled (NO), user location will not be tracked at all (neither in foreground nor on background). However, Bluetooth beacons and geofences will still be detected if this flag is set to NO.", "7-0": "moca_background_location_enabled", "7-1": "BOOL", "7-2": "YES", "7-3": "Enables/disables location tracking when the app is in background or suspended mode.\n\nThis flag has no effect if GEOLOCATION_SERVICE_ENABLED is set to NO.\n\nBy default background location tracking is enabled." }, "cols": 4, "rows": 8 } [/block] For further app permission configuration requirements please checkout [iOS'](http://developer.mocaplatform.com/docs/moca-ios-sdk-configuration#app-capabilities) and [Android's](http://developer.mocaplatform.com/docs/moca-android-sdk-configuration#setting-app-permissions) different needs.
{"_id":"5f998577fb81e800451c0313","next":{"pages":[],"description":""},"slug":"basic-examples","type":"basic","user":"559a618bdbcfd20d00710b38","version":"5f998577fb81e800451c032f","body":"The JavaScript API follows an asynchronous callback approach with hooks for events such as Enter Beacon Range, Enter Place or Display Notification Alert event. Below is a brief example of this API in use:\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Callbacks in background for Cordova Apps\",\n  \"body\": \"When the application goes from suspended state (app not running at all) to running in background, the WebView is not instantiated, thus, MOCA SDK will be unable to call your JavaScript callbacks.\\nIf the application goes from foreground to background, the WebView will be still instantiated, so all callbacks will continue working normally.\\n\\nIn order to maximize reliability, we suggest using deeplinks for showing custom content.\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/*\\n * Licensed to the Apache Software Foundation (ASF) under one\\n * or more contributor license agreements.  See the NOTICE file\\n * distributed with this work for additional information\\n * regarding copyright ownership.  The ASF licenses this file\\n * to you under the Apache License, Version 2.0 (the\\n * \\\"License\\\"); you may not use this file except in compliance\\n * with the License.  You may obtain a copy of the License at\\n *\\n * http://www.apache.org/licenses/LICENSE-2.0\\n *\\n * Unless required by applicable law or agreed to in writing,\\n * software distributed under the License is distributed on an\\n * \\\"AS IS\\\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\\n * KIND, either express or implied.  See the License for the\\n * specific language governing permissions and limitations\\n * under the License.\\n */\\n\\nconsole.log(\\\"App is on! Initializing stuff...\\\");\\nvar app = {\\n    // Application Constructor\\n    initialize: function () {\\n        this.bindEvents();\\n    },\\n    // Bind Event Listeners\\n    //\\n    // Bind any events that are required on startup. Common events are:\\n    // 'load', 'deviceready', 'offline', and 'online'.\\n\\n    bindEvents: function () {\\n        document.addEventListener('deviceready', this.onDeviceReady, false);\\n    },\\n    // deviceready Event Handler\\n    //\\n    // The scope of 'this' is the event. In order to call the 'receivedEvent'\\n    // function, we must explicitly call 'app.receivedEvent(...);'\\n    onDeviceReady: function () {\\n        app.receivedEvent('deviceready');\\n      \\t\\n      \\t//Warning: Callbacks are not reliable when the application goes\\n      \\t// from suspended state (not running), to running in backgroun\\n        MOCA.addEnterBeaconListener(onEnterBeacon);\\n        MOCA.addExitBeaconListener(onExitBeacon);\\n        MOCA.addBeaconProximityChangeListener(onBeaconProximityChange);\\n        MOCA.addEnterPlaceListener(onEnterPlace);\\n        MOCA.addExitPlaceListener(onExitPlace);\\n        MOCA.addEnterZoneListener(onEnterZone);\\n        MOCA.addExitZoneListener(onExitZone);\\n\\n        MOCA.addDisplayAlertListener(false, displayAlert);\\n        MOCA.addOpenUrlListener(false, openUrl);\\n        MOCA.addShowEmbeddedHtmlListener(false, showEmbeddedHtml);\\n        MOCA.addPlayVideoListener(false, playVideo);\\n        MOCA.addShowImageListener(false, showImage);\\n        MOCA.addAddPassbookListener(false, addPassbook);\\n        MOCA.addAddTagListener(addTag);\\n        MOCA.addPlaySoundListener(false, playSound);\\n        MOCA.addCustomActionListener(performCustomAction);\\n        MOCA.addDataReadyListener(didLoadedBeaconsData);\\n\\n\\n        getMOCAValues();\\n    },\\n    // Update DOM on a Received Event\\n    receivedEvent: function (id) {\\n        var parentElement = document.getElementById(id);\\n        var listeningElement = parentElement.querySelector('.listening');\\n        var receivedElement = parentElement.querySelector('.received');\\n\\n        listeningElement.setAttribute('style', 'display:none;');\\n        receivedElement.setAttribute('style', 'display:block;');\\n\\n        console.log('Received Event: ' + id);\\n    }\\n};\\n\\nvar getMOCAValues = function(){\\n    MOCA.placesInside(placesInside);\\n    var ver = document.getElementById(\\\"ver\\\");\\n    var appKey = document.getElementById(\\\"appKey\\\");\\n    var appSecret = document.getElementById(\\\"appSecret\\\");\\n    var logLevel = document.getElementById(\\\"logLevel\\\");\\n    MOCA.version(function(e){ ver.innerHTML = \\\"Native SDK version: <b>\\\" + e +\\\"</b>\\\"});\\n    MOCA.appKey(function(e){ appKey.innerHTML = \\\"appKey: <b>\\\" + e + \\\"</b>\\\"});\\n    MOCA.appSecret(function(e){ appSecret.innerHTML = \\\"appSecret: <b>\\\" + e + \\\"</b>\\\"});\\n    MOCA.logLevel(function(e){ logLevel.innerHTML = \\\"logLevel: <b>\\\" + e + \\\"</b>\\\"});\\n}\\n\\n//console.log = function(message) {\\n//    var logger = document.getElementById(\\\"logger\\\");\\n//    logger.innerHTML = logger.innerHTML + \\\"<li>\\\" + message + \\\"</li>\\\";\\n//};\\n\\nvar onEnterBeacon= function (e) {\\n    console.log(\\\"MOCA On Enter beacon\\\");\\n    console.log(e.detail);\\n};\\nvar onExitBeacon= function (e) {\\n    console.log(\\\"Event On exit beacon with detail \\\");\\n    console.log(e.detail);\\n};\\nvar onEnterZone = function (e) {\\n    console.log(\\\"Event On Enter Zone\\\");\\n    console.log(e.detail);\\n};\\nvar onExitZone = function (e) {\\n    console.log(\\\"Event On Exit Zone\\\");\\n    console.log(e.detail);\\n};\\nvar onBeaconProximityChange= function (e) {\\n    console.log(e);\\n    console.log(\\\"Event On Proximity change with detail \\\");\\n    console.log(e.detail);\\n};\\nvar onEnterPlace= function (e) {\\n    console.log(e);\\n    console.log(\\\"Event On enter place with detail \\\");\\n    console.log(e.detail);\\n\\n};\\nvar onExitPlace= function (e) {\\n    console.log(e);\\n    console.log(\\\"Event On exit place with detail \\\");\\n    console.log(e.detail);\\n};\\nvar performCustomAction= function (e) {\\n    console.log(\\\"Callback Perform custom action on JS \\\");\\n    console.log(e.detail);\\n};\\nvar displayAlert= function (e) {\\n    console.log(\\\"Callback display alert \\\");\\n    console.log(e.detail);\\n};\\nvar openUrl= function (e) {\\n    console.log(\\\"Callback open URL\\\");\\n    console.log(e.detail);\\n};\\nvar showEmbeddedHtml= function (e) {\\n    console.log(\\\"Callback showEmbeddedHtml\\\");\\n    console.log(e.detail);\\n};\\nvar playVideo= function (e) {\\n    console.log(\\\"callback playVideo\\\");\\n    console.log(e.detail);\\n};\\nvar showImage= function (e) {\\n    console.log(\\\"callback showImage\\\");\\n    console.log(e.detail);\\n};\\nvar addPassbook= function (e) {\\n    console.log(\\\"callback addPassbook\\\");\\n    console.log(e.detail);\\n};\\nvar addTag= function (e) {\\n    console.log(\\\"Tag Added\\\");\\n};\\nvar playSound= function (e) {\\n    console.log(\\\"callback playSound\\\");\\n    console.log(e.detail);\\n};\\n\\nvar didLoadedBeaconsData = function (e){\\n    console.log(\\\"MOCA data loaded\\\");\\n    console.log(e.detail);\\n};\\n\\nvar placesInside = function (e) {\\n    console.log(\\\"places inside: \\\");\\n    console.log(e);\\n};\\n\\napp.initialize();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","isReference":false,"category":"5f998576fb81e800451c02f7","createdAt":"2015-07-31T09:58:07.927Z","parentDoc":null,"sync_unique":"","updates":[],"__v":0,"link_url":"","excerpt":"","githubsync":"","hidden":false,"link_external":false,"order":2,"project":"559a61d2dbcfd20d00710b39","api":{"results":{"codes":[{"code":"{}","language":"json","status":200,"name":""},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"title":"Basic examples","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Basic examples


The JavaScript API follows an asynchronous callback approach with hooks for events such as Enter Beacon Range, Enter Place or Display Notification Alert event. Below is a brief example of this API in use: [block:callout] { "type": "danger", "title": "Callbacks in background for Cordova Apps", "body": "When the application goes from suspended state (app not running at all) to running in background, the WebView is not instantiated, thus, MOCA SDK will be unable to call your JavaScript callbacks.\nIf the application goes from foreground to background, the WebView will be still instantiated, so all callbacks will continue working normally.\n\nIn order to maximize reliability, we suggest using deeplinks for showing custom content." } [/block] [block:code] { "codes": [ { "code": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nconsole.log(\"App is on! Initializing stuff...\");\nvar app = {\n // Application Constructor\n initialize: function () {\n this.bindEvents();\n },\n // Bind Event Listeners\n //\n // Bind any events that are required on startup. Common events are:\n // 'load', 'deviceready', 'offline', and 'online'.\n\n bindEvents: function () {\n document.addEventListener('deviceready', this.onDeviceReady, false);\n },\n // deviceready Event Handler\n //\n // The scope of 'this' is the event. In order to call the 'receivedEvent'\n // function, we must explicitly call 'app.receivedEvent(...);'\n onDeviceReady: function () {\n app.receivedEvent('deviceready');\n \t\n \t//Warning: Callbacks are not reliable when the application goes\n \t// from suspended state (not running), to running in backgroun\n MOCA.addEnterBeaconListener(onEnterBeacon);\n MOCA.addExitBeaconListener(onExitBeacon);\n MOCA.addBeaconProximityChangeListener(onBeaconProximityChange);\n MOCA.addEnterPlaceListener(onEnterPlace);\n MOCA.addExitPlaceListener(onExitPlace);\n MOCA.addEnterZoneListener(onEnterZone);\n MOCA.addExitZoneListener(onExitZone);\n\n MOCA.addDisplayAlertListener(false, displayAlert);\n MOCA.addOpenUrlListener(false, openUrl);\n MOCA.addShowEmbeddedHtmlListener(false, showEmbeddedHtml);\n MOCA.addPlayVideoListener(false, playVideo);\n MOCA.addShowImageListener(false, showImage);\n MOCA.addAddPassbookListener(false, addPassbook);\n MOCA.addAddTagListener(addTag);\n MOCA.addPlaySoundListener(false, playSound);\n MOCA.addCustomActionListener(performCustomAction);\n MOCA.addDataReadyListener(didLoadedBeaconsData);\n\n\n getMOCAValues();\n },\n // Update DOM on a Received Event\n receivedEvent: function (id) {\n var parentElement = document.getElementById(id);\n var listeningElement = parentElement.querySelector('.listening');\n var receivedElement = parentElement.querySelector('.received');\n\n listeningElement.setAttribute('style', 'display:none;');\n receivedElement.setAttribute('style', 'display:block;');\n\n console.log('Received Event: ' + id);\n }\n};\n\nvar getMOCAValues = function(){\n MOCA.placesInside(placesInside);\n var ver = document.getElementById(\"ver\");\n var appKey = document.getElementById(\"appKey\");\n var appSecret = document.getElementById(\"appSecret\");\n var logLevel = document.getElementById(\"logLevel\");\n MOCA.version(function(e){ ver.innerHTML = \"Native SDK version: <b>\" + e +\"</b>\"});\n MOCA.appKey(function(e){ appKey.innerHTML = \"appKey: <b>\" + e + \"</b>\"});\n MOCA.appSecret(function(e){ appSecret.innerHTML = \"appSecret: <b>\" + e + \"</b>\"});\n MOCA.logLevel(function(e){ logLevel.innerHTML = \"logLevel: <b>\" + e + \"</b>\"});\n}\n\n//console.log = function(message) {\n// var logger = document.getElementById(\"logger\");\n// logger.innerHTML = logger.innerHTML + \"<li>\" + message + \"</li>\";\n//};\n\nvar onEnterBeacon= function (e) {\n console.log(\"MOCA On Enter beacon\");\n console.log(e.detail);\n};\nvar onExitBeacon= function (e) {\n console.log(\"Event On exit beacon with detail \");\n console.log(e.detail);\n};\nvar onEnterZone = function (e) {\n console.log(\"Event On Enter Zone\");\n console.log(e.detail);\n};\nvar onExitZone = function (e) {\n console.log(\"Event On Exit Zone\");\n console.log(e.detail);\n};\nvar onBeaconProximityChange= function (e) {\n console.log(e);\n console.log(\"Event On Proximity change with detail \");\n console.log(e.detail);\n};\nvar onEnterPlace= function (e) {\n console.log(e);\n console.log(\"Event On enter place with detail \");\n console.log(e.detail);\n\n};\nvar onExitPlace= function (e) {\n console.log(e);\n console.log(\"Event On exit place with detail \");\n console.log(e.detail);\n};\nvar performCustomAction= function (e) {\n console.log(\"Callback Perform custom action on JS \");\n console.log(e.detail);\n};\nvar displayAlert= function (e) {\n console.log(\"Callback display alert \");\n console.log(e.detail);\n};\nvar openUrl= function (e) {\n console.log(\"Callback open URL\");\n console.log(e.detail);\n};\nvar showEmbeddedHtml= function (e) {\n console.log(\"Callback showEmbeddedHtml\");\n console.log(e.detail);\n};\nvar playVideo= function (e) {\n console.log(\"callback playVideo\");\n console.log(e.detail);\n};\nvar showImage= function (e) {\n console.log(\"callback showImage\");\n console.log(e.detail);\n};\nvar addPassbook= function (e) {\n console.log(\"callback addPassbook\");\n console.log(e.detail);\n};\nvar addTag= function (e) {\n console.log(\"Tag Added\");\n};\nvar playSound= function (e) {\n console.log(\"callback playSound\");\n console.log(e.detail);\n};\n\nvar didLoadedBeaconsData = function (e){\n console.log(\"MOCA data loaded\");\n console.log(e.detail);\n};\n\nvar placesInside = function (e) {\n console.log(\"places inside: \");\n console.log(e);\n};\n\napp.initialize();", "language": "javascript" } ] } [/block]
The JavaScript API follows an asynchronous callback approach with hooks for events such as Enter Beacon Range, Enter Place or Display Notification Alert event. Below is a brief example of this API in use: [block:callout] { "type": "danger", "title": "Callbacks in background for Cordova Apps", "body": "When the application goes from suspended state (app not running at all) to running in background, the WebView is not instantiated, thus, MOCA SDK will be unable to call your JavaScript callbacks.\nIf the application goes from foreground to background, the WebView will be still instantiated, so all callbacks will continue working normally.\n\nIn order to maximize reliability, we suggest using deeplinks for showing custom content." } [/block] [block:code] { "codes": [ { "code": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nconsole.log(\"App is on! Initializing stuff...\");\nvar app = {\n // Application Constructor\n initialize: function () {\n this.bindEvents();\n },\n // Bind Event Listeners\n //\n // Bind any events that are required on startup. Common events are:\n // 'load', 'deviceready', 'offline', and 'online'.\n\n bindEvents: function () {\n document.addEventListener('deviceready', this.onDeviceReady, false);\n },\n // deviceready Event Handler\n //\n // The scope of 'this' is the event. In order to call the 'receivedEvent'\n // function, we must explicitly call 'app.receivedEvent(...);'\n onDeviceReady: function () {\n app.receivedEvent('deviceready');\n \t\n \t//Warning: Callbacks are not reliable when the application goes\n \t// from suspended state (not running), to running in backgroun\n MOCA.addEnterBeaconListener(onEnterBeacon);\n MOCA.addExitBeaconListener(onExitBeacon);\n MOCA.addBeaconProximityChangeListener(onBeaconProximityChange);\n MOCA.addEnterPlaceListener(onEnterPlace);\n MOCA.addExitPlaceListener(onExitPlace);\n MOCA.addEnterZoneListener(onEnterZone);\n MOCA.addExitZoneListener(onExitZone);\n\n MOCA.addDisplayAlertListener(false, displayAlert);\n MOCA.addOpenUrlListener(false, openUrl);\n MOCA.addShowEmbeddedHtmlListener(false, showEmbeddedHtml);\n MOCA.addPlayVideoListener(false, playVideo);\n MOCA.addShowImageListener(false, showImage);\n MOCA.addAddPassbookListener(false, addPassbook);\n MOCA.addAddTagListener(addTag);\n MOCA.addPlaySoundListener(false, playSound);\n MOCA.addCustomActionListener(performCustomAction);\n MOCA.addDataReadyListener(didLoadedBeaconsData);\n\n\n getMOCAValues();\n },\n // Update DOM on a Received Event\n receivedEvent: function (id) {\n var parentElement = document.getElementById(id);\n var listeningElement = parentElement.querySelector('.listening');\n var receivedElement = parentElement.querySelector('.received');\n\n listeningElement.setAttribute('style', 'display:none;');\n receivedElement.setAttribute('style', 'display:block;');\n\n console.log('Received Event: ' + id);\n }\n};\n\nvar getMOCAValues = function(){\n MOCA.placesInside(placesInside);\n var ver = document.getElementById(\"ver\");\n var appKey = document.getElementById(\"appKey\");\n var appSecret = document.getElementById(\"appSecret\");\n var logLevel = document.getElementById(\"logLevel\");\n MOCA.version(function(e){ ver.innerHTML = \"Native SDK version: <b>\" + e +\"</b>\"});\n MOCA.appKey(function(e){ appKey.innerHTML = \"appKey: <b>\" + e + \"</b>\"});\n MOCA.appSecret(function(e){ appSecret.innerHTML = \"appSecret: <b>\" + e + \"</b>\"});\n MOCA.logLevel(function(e){ logLevel.innerHTML = \"logLevel: <b>\" + e + \"</b>\"});\n}\n\n//console.log = function(message) {\n// var logger = document.getElementById(\"logger\");\n// logger.innerHTML = logger.innerHTML + \"<li>\" + message + \"</li>\";\n//};\n\nvar onEnterBeacon= function (e) {\n console.log(\"MOCA On Enter beacon\");\n console.log(e.detail);\n};\nvar onExitBeacon= function (e) {\n console.log(\"Event On exit beacon with detail \");\n console.log(e.detail);\n};\nvar onEnterZone = function (e) {\n console.log(\"Event On Enter Zone\");\n console.log(e.detail);\n};\nvar onExitZone = function (e) {\n console.log(\"Event On Exit Zone\");\n console.log(e.detail);\n};\nvar onBeaconProximityChange= function (e) {\n console.log(e);\n console.log(\"Event On Proximity change with detail \");\n console.log(e.detail);\n};\nvar onEnterPlace= function (e) {\n console.log(e);\n console.log(\"Event On enter place with detail \");\n console.log(e.detail);\n\n};\nvar onExitPlace= function (e) {\n console.log(e);\n console.log(\"Event On exit place with detail \");\n console.log(e.detail);\n};\nvar performCustomAction= function (e) {\n console.log(\"Callback Perform custom action on JS \");\n console.log(e.detail);\n};\nvar displayAlert= function (e) {\n console.log(\"Callback display alert \");\n console.log(e.detail);\n};\nvar openUrl= function (e) {\n console.log(\"Callback open URL\");\n console.log(e.detail);\n};\nvar showEmbeddedHtml= function (e) {\n console.log(\"Callback showEmbeddedHtml\");\n console.log(e.detail);\n};\nvar playVideo= function (e) {\n console.log(\"callback playVideo\");\n console.log(e.detail);\n};\nvar showImage= function (e) {\n console.log(\"callback showImage\");\n console.log(e.detail);\n};\nvar addPassbook= function (e) {\n console.log(\"callback addPassbook\");\n console.log(e.detail);\n};\nvar addTag= function (e) {\n console.log(\"Tag Added\");\n};\nvar playSound= function (e) {\n console.log(\"callback playSound\");\n console.log(e.detail);\n};\n\nvar didLoadedBeaconsData = function (e){\n console.log(\"MOCA data loaded\");\n console.log(e.detail);\n};\n\nvar placesInside = function (e) {\n console.log(\"places inside: \");\n console.log(e);\n};\n\napp.initialize();", "language": "javascript" } ] } [/block]
{"_id":"5f998577fb81e800451c0315","link_external":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","excerpt":"","title":"Common issues / Troubleshooting","user":"559a618bdbcfd20d00710b38","hidden":false,"order":4,"parentDoc":null,"sync_unique":"","type":"basic","updates":[],"__v":0,"githubsync":"","category":"5f998576fb81e800451c02f7","createdAt":"2016-07-26T17:26:22.879Z","isReference":false,"next":{"pages":[],"description":""},"slug":"common-issues-troubleshooting","version":"5f998577fb81e800451c032f","api":{"params":[],"url":"","results":{"codes":[{"status":200,"name":"","code":"{}","language":"json"},{"code":"{}","language":"json","status":400,"name":""}]},"settings":"","auth":"required"},"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Dependencies conflict (Android)\"\n}\n[/block]\n##Symptom\nYou receive the following error message at compile time:\n\n```\n:transformClassesWithDexForDebug\nUNEXPECTED TOP-LEVEL EXCEPTION:\ncom.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzr;\n```\n\n##Solution\n\nMOCA Plugin for Cordova / PhoneGap requires the following dependencies on Android:\n- Google Play Services (GPSS) - Cloud Messaging (GCM)\n- GPSS - Location Services\n- GPSS - Ads\n- MessagePack\n\nIf you are using other plugins within your project, it is common that some of these plugins rely also on GPSS for some functionality. The problem arises when any of these libraries use a different version of GPSS.\n\nMOCA Plugin expects at least GPSS version 8.3. We provide you the plugin with this version in the plugin configuration, so you can have predictable builds in the future. \n\nIn order to fix this issue, please use one of the following solutions:\n\nOption A:\n\nChange the `mocabuild.gradle` file within the plugin folder and change **all** the versions to the latest one, bear in mind that **your other plugins should also use the same version**.\n\nOption B:\n\nCreate a file called `build-extras.gradle` in the following folder `your_app_name > platforms > android` and paste the following code there.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n\\n// When set, this function allows code to run at the end of `build.gradle`\\next.postBuildExtras = {\\n    configurations.all {\\n\\t\\tresolutionStrategy {\\n      \\t//Google Cloud Messaging\\n    \\t\\tforce 'com.google.android.gms:play-services-gcm:+'\\n    \\t\\t\\n      \\t//Google Location, Activity Recognition, and Places\\n   \\t\\t\\tforce 'com.google.android.gms:play-services-location:+'\\n\\n    \\t\\t//Google Mobile Ads\\n   \\t\\t\\tforce 'com.google.android.gms:play-services-ads:+'\\n\\t\\t}\\n\\t}\\n}\\n\",\n      \"language\": \"groovy\",\n      \"name\": \"build-extras.gradle\"\n    }\n  ]\n}\n[/block]\nIf there is any other plugin that uses any part of GPSS, you should include it here as well, and remember: All GPSS dependencies must use the same version, otherwise you will get errors at Compile or at RunTime.\n\nBelow you will find a list of possible GPSS dependencies\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"# Google+\\nforce 'com.google.android.gms:play-services-plus:+'\\n# Google Account Login\\nforce 'com.google.android.gms:play-services-auth:+'\\n# Google Actions, Base Client Library\\nforce 'com.google.android.gms:play-services-base:+'\\n# Google Address API\\nforce 'com.google.android.gms:play-services-identity:+'\\n# Google App Indexing\\nforce 'com.google.android.gms:play-services-appindexing:+'\\n# Google App Invites\\nforce 'com.google.android.gms:play-services-appinvite:+'\\n# Google Analytics\\nforce 'com.google.android.gms:play-services-analytics:+'\\n# Google Cast\\nforce 'com.google.android.gms:play-services-cast:+'\\n# Google Cloud Messaging\\nforce 'com.google.android.gms:play-services-gcm:+'\\n# Google Drive\\nforce 'com.google.android.gms:play-services-drive:+'\\n# Google Fit\\nforce 'com.google.android.gms:play-services-fitness:+'\\n# Google Location, Activity Recognition, and Places\\nforce 'com.google.android.gms:play-services-location:+'\\n# Google Maps\\nforce 'com.google.android.gms:play-services-maps:+'\\n# Google Mobile Ads\\nforce 'com.google.android.gms:play-services-ads:+'\\n# Mobile Vision\\nforce 'com.google.android.gms:play-services-vision:+'\\n# Google Nearby\\nforce 'com.google.android.gms:play-services-nearby:+'\\n# Google Panorama Viewer\\nforce 'com.google.android.gms:play-services-panorama:+'\\n# Google Play Game services\\nforce 'com.google.android.gms:play-services-games:+'\\n# SafetyNet\\nforce 'com.google.android.gms:play-services-safetynet:+'\\n# Android Pay\\nforce 'com.google.android.gms:play-services-wallet:+'\\n# Android Wear\\nforce 'com.google.android.gms:play-services-wearable:+'\",\n      \"language\": \"groovy\",\n      \"name\": \"GPSS dependency examples\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Application crashes at startup\"\n}\n[/block]\n##Symptom\n\nApplication crashes at startup with the following error message\n\n`java.lang.ClassCastException: android.app.Application cannot be cast to com.innoquant.moca.phonegap.MOCApp`\n\n##Solution\n\nMOCA Plugin works even if the app is not running, in order to achieve this functionality, it requires a class to be declared in your `AndroidManifest.xml` `application` tag. If the Android platform is already created when you installed MOCA Plugin, this is done automatically by the installation scripts, however it may not work if there is a conflict with other plugin that has the same requirement, or if the android platform is added afterwards.\n\nOpen your `AndroidManifest.xml` and check the `application` tag, you should observe something similar to this example (notice the `android:name=\"com.innoquant.phonegap.MOCApp\"`)\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/4dbf58c-android-name.png\",\n        \"android-name.png\",\n        579,\n        115,\n        \"#30302f\"\n      ]\n    }\n  ]\n}\n[/block]\n###Case 1: There is no `android:name` tag.\n\n####Solution\n- Just add the tag as shown in the image above.\n\n###Case 2: There are two `android:name` tags, or the class declared is from another plugin.\n\n####Solution\n- In this case the solution is not as straightforward and will require some Java coding in the project.\n\nIf there are two plugins with this requirement within your project, you will need to merge these two classes manually. If you have experience coding Java, just go ahead, create a new class with a name of your preference, merge all functionality in a single class (or create a proxy class that instantiates both classes) and declare this new class in the application tag.\n\nIn any case, if you are in this particular case, please open a [support ticket](mailto:[email protected]). We would like to study in detail any more conflicts that may arise with the 3rd party plugin.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Other Building errors\"\n}\n[/block]\n##Symptom\n\nYou receive the following error at compile time.\n\n```\n.../HelloWorld/platforms/android/build/intermediates/res/debug/values-v23/values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse\n\n...HelloWorld/platforms/android/build/intermediates/res/debug/values-v23/values.xml:20: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.\n```\n\n####Solution\n\nMOCA Plugin requires project to be compiled against Android API level 26 (Android Oreo). Please check you have included the min and target in your `config.xml` versions as follows:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<preference name=\\\"android-minSdkVersion\\\" value=\\\"14\\\" />\\n<preference name=\\\"android-targetSdkVersion\\\" value=\\\"26\\\" />\",\n      \"language\": \"xml\"\n    }\n  ]\n}\n[/block]\nIf problem persists, please check the following file:\n\n`YOUR_APP_FOLDER/platforms/android/project.properties`\n\nAnd change the configuration if needed:\n\n`target=android-26`","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Common issues / Troubleshooting


[block:api-header] { "type": "basic", "title": "Dependencies conflict (Android)" } [/block] ##Symptom You receive the following error message at compile time: ``` :transformClassesWithDexForDebug UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzr; ``` ##Solution MOCA Plugin for Cordova / PhoneGap requires the following dependencies on Android: - Google Play Services (GPSS) - Cloud Messaging (GCM) - GPSS - Location Services - GPSS - Ads - MessagePack If you are using other plugins within your project, it is common that some of these plugins rely also on GPSS for some functionality. The problem arises when any of these libraries use a different version of GPSS. MOCA Plugin expects at least GPSS version 8.3. We provide you the plugin with this version in the plugin configuration, so you can have predictable builds in the future. In order to fix this issue, please use one of the following solutions: Option A: Change the `mocabuild.gradle` file within the plugin folder and change **all** the versions to the latest one, bear in mind that **your other plugins should also use the same version**. Option B: Create a file called `build-extras.gradle` in the following folder `your_app_name > platforms > android` and paste the following code there. [block:code] { "codes": [ { "code": "\n\n// When set, this function allows code to run at the end of `build.gradle`\next.postBuildExtras = {\n configurations.all {\n\t\tresolutionStrategy {\n \t//Google Cloud Messaging\n \t\tforce 'com.google.android.gms:play-services-gcm:+'\n \t\t\n \t//Google Location, Activity Recognition, and Places\n \t\t\tforce 'com.google.android.gms:play-services-location:+'\n\n \t\t//Google Mobile Ads\n \t\t\tforce 'com.google.android.gms:play-services-ads:+'\n\t\t}\n\t}\n}\n", "language": "groovy", "name": "build-extras.gradle" } ] } [/block] If there is any other plugin that uses any part of GPSS, you should include it here as well, and remember: All GPSS dependencies must use the same version, otherwise you will get errors at Compile or at RunTime. Below you will find a list of possible GPSS dependencies [block:code] { "codes": [ { "code": "# Google+\nforce 'com.google.android.gms:play-services-plus:+'\n# Google Account Login\nforce 'com.google.android.gms:play-services-auth:+'\n# Google Actions, Base Client Library\nforce 'com.google.android.gms:play-services-base:+'\n# Google Address API\nforce 'com.google.android.gms:play-services-identity:+'\n# Google App Indexing\nforce 'com.google.android.gms:play-services-appindexing:+'\n# Google App Invites\nforce 'com.google.android.gms:play-services-appinvite:+'\n# Google Analytics\nforce 'com.google.android.gms:play-services-analytics:+'\n# Google Cast\nforce 'com.google.android.gms:play-services-cast:+'\n# Google Cloud Messaging\nforce 'com.google.android.gms:play-services-gcm:+'\n# Google Drive\nforce 'com.google.android.gms:play-services-drive:+'\n# Google Fit\nforce 'com.google.android.gms:play-services-fitness:+'\n# Google Location, Activity Recognition, and Places\nforce 'com.google.android.gms:play-services-location:+'\n# Google Maps\nforce 'com.google.android.gms:play-services-maps:+'\n# Google Mobile Ads\nforce 'com.google.android.gms:play-services-ads:+'\n# Mobile Vision\nforce 'com.google.android.gms:play-services-vision:+'\n# Google Nearby\nforce 'com.google.android.gms:play-services-nearby:+'\n# Google Panorama Viewer\nforce 'com.google.android.gms:play-services-panorama:+'\n# Google Play Game services\nforce 'com.google.android.gms:play-services-games:+'\n# SafetyNet\nforce 'com.google.android.gms:play-services-safetynet:+'\n# Android Pay\nforce 'com.google.android.gms:play-services-wallet:+'\n# Android Wear\nforce 'com.google.android.gms:play-services-wearable:+'", "language": "groovy", "name": "GPSS dependency examples" } ] } [/block] [block:api-header] { "type": "basic", "title": "Application crashes at startup" } [/block] ##Symptom Application crashes at startup with the following error message `java.lang.ClassCastException: android.app.Application cannot be cast to com.innoquant.moca.phonegap.MOCApp` ##Solution MOCA Plugin works even if the app is not running, in order to achieve this functionality, it requires a class to be declared in your `AndroidManifest.xml` `application` tag. If the Android platform is already created when you installed MOCA Plugin, this is done automatically by the installation scripts, however it may not work if there is a conflict with other plugin that has the same requirement, or if the android platform is added afterwards. Open your `AndroidManifest.xml` and check the `application` tag, you should observe something similar to this example (notice the `android:name="com.innoquant.phonegap.MOCApp"`) [block:image] { "images": [ { "image": [ "https://files.readme.io/4dbf58c-android-name.png", "android-name.png", 579, 115, "#30302f" ] } ] } [/block] ###Case 1: There is no `android:name` tag. ####Solution - Just add the tag as shown in the image above. ###Case 2: There are two `android:name` tags, or the class declared is from another plugin. ####Solution - In this case the solution is not as straightforward and will require some Java coding in the project. If there are two plugins with this requirement within your project, you will need to merge these two classes manually. If you have experience coding Java, just go ahead, create a new class with a name of your preference, merge all functionality in a single class (or create a proxy class that instantiates both classes) and declare this new class in the application tag. In any case, if you are in this particular case, please open a [support ticket](mailto:[email protected]). We would like to study in detail any more conflicts that may arise with the 3rd party plugin. [block:api-header] { "type": "basic", "title": "Other Building errors" } [/block] ##Symptom You receive the following error at compile time. ``` .../HelloWorld/platforms/android/build/intermediates/res/debug/values-v23/values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse ...HelloWorld/platforms/android/build/intermediates/res/debug/values-v23/values.xml:20: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'. ``` ####Solution MOCA Plugin requires project to be compiled against Android API level 26 (Android Oreo). Please check you have included the min and target in your `config.xml` versions as follows: [block:code] { "codes": [ { "code": "<preference name=\"android-minSdkVersion\" value=\"14\" />\n<preference name=\"android-targetSdkVersion\" value=\"26\" />", "language": "xml" } ] } [/block] If problem persists, please check the following file: `YOUR_APP_FOLDER/platforms/android/project.properties` And change the configuration if needed: `target=android-26`
[block:api-header] { "type": "basic", "title": "Dependencies conflict (Android)" } [/block] ##Symptom You receive the following error message at compile time: ``` :transformClassesWithDexForDebug UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzr; ``` ##Solution MOCA Plugin for Cordova / PhoneGap requires the following dependencies on Android: - Google Play Services (GPSS) - Cloud Messaging (GCM) - GPSS - Location Services - GPSS - Ads - MessagePack If you are using other plugins within your project, it is common that some of these plugins rely also on GPSS for some functionality. The problem arises when any of these libraries use a different version of GPSS. MOCA Plugin expects at least GPSS version 8.3. We provide you the plugin with this version in the plugin configuration, so you can have predictable builds in the future. In order to fix this issue, please use one of the following solutions: Option A: Change the `mocabuild.gradle` file within the plugin folder and change **all** the versions to the latest one, bear in mind that **your other plugins should also use the same version**. Option B: Create a file called `build-extras.gradle` in the following folder `your_app_name > platforms > android` and paste the following code there. [block:code] { "codes": [ { "code": "\n\n// When set, this function allows code to run at the end of `build.gradle`\next.postBuildExtras = {\n configurations.all {\n\t\tresolutionStrategy {\n \t//Google Cloud Messaging\n \t\tforce 'com.google.android.gms:play-services-gcm:+'\n \t\t\n \t//Google Location, Activity Recognition, and Places\n \t\t\tforce 'com.google.android.gms:play-services-location:+'\n\n \t\t//Google Mobile Ads\n \t\t\tforce 'com.google.android.gms:play-services-ads:+'\n\t\t}\n\t}\n}\n", "language": "groovy", "name": "build-extras.gradle" } ] } [/block] If there is any other plugin that uses any part of GPSS, you should include it here as well, and remember: All GPSS dependencies must use the same version, otherwise you will get errors at Compile or at RunTime. Below you will find a list of possible GPSS dependencies [block:code] { "codes": [ { "code": "# Google+\nforce 'com.google.android.gms:play-services-plus:+'\n# Google Account Login\nforce 'com.google.android.gms:play-services-auth:+'\n# Google Actions, Base Client Library\nforce 'com.google.android.gms:play-services-base:+'\n# Google Address API\nforce 'com.google.android.gms:play-services-identity:+'\n# Google App Indexing\nforce 'com.google.android.gms:play-services-appindexing:+'\n# Google App Invites\nforce 'com.google.android.gms:play-services-appinvite:+'\n# Google Analytics\nforce 'com.google.android.gms:play-services-analytics:+'\n# Google Cast\nforce 'com.google.android.gms:play-services-cast:+'\n# Google Cloud Messaging\nforce 'com.google.android.gms:play-services-gcm:+'\n# Google Drive\nforce 'com.google.android.gms:play-services-drive:+'\n# Google Fit\nforce 'com.google.android.gms:play-services-fitness:+'\n# Google Location, Activity Recognition, and Places\nforce 'com.google.android.gms:play-services-location:+'\n# Google Maps\nforce 'com.google.android.gms:play-services-maps:+'\n# Google Mobile Ads\nforce 'com.google.android.gms:play-services-ads:+'\n# Mobile Vision\nforce 'com.google.android.gms:play-services-vision:+'\n# Google Nearby\nforce 'com.google.android.gms:play-services-nearby:+'\n# Google Panorama Viewer\nforce 'com.google.android.gms:play-services-panorama:+'\n# Google Play Game services\nforce 'com.google.android.gms:play-services-games:+'\n# SafetyNet\nforce 'com.google.android.gms:play-services-safetynet:+'\n# Android Pay\nforce 'com.google.android.gms:play-services-wallet:+'\n# Android Wear\nforce 'com.google.android.gms:play-services-wearable:+'", "language": "groovy", "name": "GPSS dependency examples" } ] } [/block] [block:api-header] { "type": "basic", "title": "Application crashes at startup" } [/block] ##Symptom Application crashes at startup with the following error message `java.lang.ClassCastException: android.app.Application cannot be cast to com.innoquant.moca.phonegap.MOCApp` ##Solution MOCA Plugin works even if the app is not running, in order to achieve this functionality, it requires a class to be declared in your `AndroidManifest.xml` `application` tag. If the Android platform is already created when you installed MOCA Plugin, this is done automatically by the installation scripts, however it may not work if there is a conflict with other plugin that has the same requirement, or if the android platform is added afterwards. Open your `AndroidManifest.xml` and check the `application` tag, you should observe something similar to this example (notice the `android:name="com.innoquant.phonegap.MOCApp"`) [block:image] { "images": [ { "image": [ "https://files.readme.io/4dbf58c-android-name.png", "android-name.png", 579, 115, "#30302f" ] } ] } [/block] ###Case 1: There is no `android:name` tag. ####Solution - Just add the tag as shown in the image above. ###Case 2: There are two `android:name` tags, or the class declared is from another plugin. ####Solution - In this case the solution is not as straightforward and will require some Java coding in the project. If there are two plugins with this requirement within your project, you will need to merge these two classes manually. If you have experience coding Java, just go ahead, create a new class with a name of your preference, merge all functionality in a single class (or create a proxy class that instantiates both classes) and declare this new class in the application tag. In any case, if you are in this particular case, please open a [support ticket](mailto:[email protected]). We would like to study in detail any more conflicts that may arise with the 3rd party plugin. [block:api-header] { "type": "basic", "title": "Other Building errors" } [/block] ##Symptom You receive the following error at compile time. ``` .../HelloWorld/platforms/android/build/intermediates/res/debug/values-v23/values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse ...HelloWorld/platforms/android/build/intermediates/res/debug/values-v23/values.xml:20: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'. ``` ####Solution MOCA Plugin requires project to be compiled against Android API level 26 (Android Oreo). Please check you have included the min and target in your `config.xml` versions as follows: [block:code] { "codes": [ { "code": "<preference name=\"android-minSdkVersion\" value=\"14\" />\n<preference name=\"android-targetSdkVersion\" value=\"26\" />", "language": "xml" } ] } [/block] If problem persists, please check the following file: `YOUR_APP_FOLDER/platforms/android/project.properties` And change the configuration if needed: `target=android-26`
{"_id":"5f998577fb81e800451c032a","project":"559a61d2dbcfd20d00710b39","version":"5f998577fb81e800451c032f","category":"5f998576fb81e800451c02f7","user":"559a618bdbcfd20d00710b38","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-09-25T14:28:37.357Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"status":400,"language":"json","code":"{}","name":""}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":5,"body":"Tags are a way to add information to the user's profile. You can set Tags with a fixed value, or you can use them as counters. Below, you will find the Javascript API for this feature.\n[block:api-header]\n{\n  \"title\": \"Ionic\"\n}\n[/block]\nIf you are using Ionic-angular, you will need to manually reference MOCA in your code before making any API call, add the following line in your `app.component.ts`:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//TypeScript\\n\\ndeclare var MOCA:any;\\n\",\n      \"language\": \"javascript\",\n      \"name\": \"TypeScript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Adding a Tag\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\t//Adding a tag with no specific value, value will be set to =1\\n    var instance = MOCA.currentInstance();\\n    instance.addTag(\\\"Yellow\\\");\\n\\n\\t///Increasing / Decreasing / setting the value of a Tag\\n    instance.addTag(\\\"Green\\\",\\\"+2\\\");\\n    instance.addTag(\\\"Blue\\\",\\\"=2\\\");\\n    instance.addTag(\\\"Red\\\",\\\"-1\\\");\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Removing a Tag\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\tvar instance = MOCA.currentInstance();\\n  instance.removeTag(\\\"Yellow\\\");\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Check if Tag exists\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\t//Check whether the instance contains a tag\\n\\tvar instance = MOCA.currentInstance();\\n  instance.containsTag(\\\"Yellow\\\", listenerFunction);\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Getting a Tag value\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\t//Get Tag Value\\n\\tvar instance = MOCA.currentInstance();\\n\\tinstance.getTagValue(\\\"Yellow\\\", listenerFunction);\\n\\n\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","excerpt":"","slug":"tag-api-1","type":"basic","title":"Tag API","__v":0,"parentDoc":null,"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Tag API


Tags are a way to add information to the user's profile. You can set Tags with a fixed value, or you can use them as counters. Below, you will find the Javascript API for this feature. [block:api-header] { "title": "Ionic" } [/block] If you are using Ionic-angular, you will need to manually reference MOCA in your code before making any API call, add the following line in your `app.component.ts`: [block:code] { "codes": [ { "code": "//TypeScript\n\ndeclare var MOCA:any;\n", "language": "javascript", "name": "TypeScript" } ] } [/block] [block:api-header] { "title": "Adding a Tag" } [/block] [block:code] { "codes": [ { "code": "\t//Adding a tag with no specific value, value will be set to =1\n var instance = MOCA.currentInstance();\n instance.addTag(\"Yellow\");\n\n\t///Increasing / Decreasing / setting the value of a Tag\n instance.addTag(\"Green\",\"+2\");\n instance.addTag(\"Blue\",\"=2\");\n instance.addTag(\"Red\",\"-1\");\n", "language": "javascript" } ] } [/block] [block:api-header] { "title": "Removing a Tag" } [/block] [block:code] { "codes": [ { "code": "\tvar instance = MOCA.currentInstance();\n instance.removeTag(\"Yellow\");", "language": "javascript" } ] } [/block] [block:api-header] { "title": "Check if Tag exists" } [/block] [block:code] { "codes": [ { "code": "\t//Check whether the instance contains a tag\n\tvar instance = MOCA.currentInstance();\n instance.containsTag(\"Yellow\", listenerFunction);\n", "language": "javascript" } ] } [/block] [block:api-header] { "title": "Getting a Tag value" } [/block] [block:code] { "codes": [ { "code": "\t//Get Tag Value\n\tvar instance = MOCA.currentInstance();\n\tinstance.getTagValue(\"Yellow\", listenerFunction);\n\n\n", "language": "javascript" } ] } [/block]
Tags are a way to add information to the user's profile. You can set Tags with a fixed value, or you can use them as counters. Below, you will find the Javascript API for this feature. [block:api-header] { "title": "Ionic" } [/block] If you are using Ionic-angular, you will need to manually reference MOCA in your code before making any API call, add the following line in your `app.component.ts`: [block:code] { "codes": [ { "code": "//TypeScript\n\ndeclare var MOCA:any;\n", "language": "javascript", "name": "TypeScript" } ] } [/block] [block:api-header] { "title": "Adding a Tag" } [/block] [block:code] { "codes": [ { "code": "\t//Adding a tag with no specific value, value will be set to =1\n var instance = MOCA.currentInstance();\n instance.addTag(\"Yellow\");\n\n\t///Increasing / Decreasing / setting the value of a Tag\n instance.addTag(\"Green\",\"+2\");\n instance.addTag(\"Blue\",\"=2\");\n instance.addTag(\"Red\",\"-1\");\n", "language": "javascript" } ] } [/block] [block:api-header] { "title": "Removing a Tag" } [/block] [block:code] { "codes": [ { "code": "\tvar instance = MOCA.currentInstance();\n instance.removeTag(\"Yellow\");", "language": "javascript" } ] } [/block] [block:api-header] { "title": "Check if Tag exists" } [/block] [block:code] { "codes": [ { "code": "\t//Check whether the instance contains a tag\n\tvar instance = MOCA.currentInstance();\n instance.containsTag(\"Yellow\", listenerFunction);\n", "language": "javascript" } ] } [/block] [block:api-header] { "title": "Getting a Tag value" } [/block] [block:code] { "codes": [ { "code": "\t//Get Tag Value\n\tvar instance = MOCA.currentInstance();\n\tinstance.getTagValue(\"Yellow\", listenerFunction);\n\n\n", "language": "javascript" } ] } [/block]
{"_id":"5f998577fb81e800451c030d","link_external":false,"link_url":"","slug":"javascript-api-usage","sync_unique":"","type":"basic","api":{"params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required"},"githubsync":"","parentDoc":null,"title":"JavaScript API Usage","updates":[],"body":"###Print MOCA SDK version\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.version (function (version) {\\n      // ...\\n  });\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get MOCA app key:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n  MOCA.appKey (function (key) {\\n     // ...\\n  });\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get MOCA app secret:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n  MOCA.appSecret (function (secret) {\\n     // ...\\n  });\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Check if MOCA was initialized:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  if (MOCA.initialized(function (isInited)) {\\n      if (isInited) {\\n         // ...\\n      } else {\\n         // ...\\n      }\\n  }\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Check if MOCA proximity is enabled:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  if (MOCA.proximityEnabled(function (enabled)) {\\n      if (enabled) {\\n         // ...\\n      } else {\\n         // ...\\n      }\\n  }\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Enable MOCA proximity:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.setProximityEnabled(true, function () {\\n\\t// ...\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get log level:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.logLevel (function (level) {\\n      // ...\\n  });   \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Set log level\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  // var level = \\\"info\\\" | \\\"debug\\\" | \\\"trace\\\" | \\\"warning\\\" | \\\"error\\\" | \\\"off\\\"\\n  MOCA.setLogLevel (level, function () {\\n      // ...\\n  });    \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Login user:\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Login the user with every app startup\",\n  \"body\": \"After launching the app, check whether the user is still logged in or not. If the user is still logged in, perform a new 'MOCA login'\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCA.login (userId, function () {\\n\\t// ...\\n});      \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Logout current user:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.logout (function () {\\n      // ...\\n  });      \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Check if user has been logged in:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.userLoggedIn (function (isLoggedIn) {\\n      if (isLoggedIn) {\\n         // ...\\n      } else {\\n         // ...\\n      }\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Perform asynchronous fetch of beacons/campaigns data from cloud:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.performFetch (function (data) {\\n      // ...\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get custom property by key:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n  MOCA.customProperty (key, function (dictionary) {\\n      // ...dictionary -> {\\\"requestedProperty\\\": \\\"value\\\"} or {} if not found\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n###Set custom property (key/value):\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n  MOCA.setCustomProperty (key, value, function () {\\n      // ...\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get MOCA instance unique ID:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n  MOCAInstance.identifier (function (iid) {\\n      // ...\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get app session number:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n  MOCAInstance.session (function (sessionNumber) {\\n      // ...\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get device push token\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCAInstance.deviceToken (function (token) {\\n      // ...\\n  });      \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Get place device is currently visiting\n\n- It returns an array with the place(s) you are currently visiting\n- Combine this call with the `addEnterPlaceListener` callback to ensure you detect places correctly.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" MOCA.placesInside(function (e) {\\n    console.log(\\\"places inside: \\\");\\n    console.log(e);\\n});\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","excerpt":"","hidden":false,"isReference":false,"order":0,"user":"559a618bdbcfd20d00710b38","version":"5f998577fb81e800451c032f","__v":0,"category":"5f998576fb81e800451c02f8","createdAt":"2015-07-31T09:58:36.554Z","next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

JavaScript API Usage


###Print MOCA SDK version [block:code] { "codes": [ { "code": " MOCA.version (function (version) {\n // ...\n });", "language": "javascript" } ] } [/block] ###Get MOCA app key: [block:code] { "codes": [ { "code": "\n MOCA.appKey (function (key) {\n // ...\n });\n", "language": "javascript" } ] } [/block] ###Get MOCA app secret: [block:code] { "codes": [ { "code": "\n MOCA.appSecret (function (secret) {\n // ...\n });\n", "language": "javascript" } ] } [/block] ###Check if MOCA was initialized: [block:code] { "codes": [ { "code": " if (MOCA.initialized(function (isInited)) {\n if (isInited) {\n // ...\n } else {\n // ...\n }\n }", "language": "javascript" } ] } [/block] ###Check if MOCA proximity is enabled: [block:code] { "codes": [ { "code": " if (MOCA.proximityEnabled(function (enabled)) {\n if (enabled) {\n // ...\n } else {\n // ...\n }\n }\n", "language": "javascript" } ] } [/block] ###Enable MOCA proximity: [block:code] { "codes": [ { "code": "MOCA.setProximityEnabled(true, function () {\n\t// ...\n});", "language": "javascript" } ] } [/block] ###Get log level: [block:code] { "codes": [ { "code": " MOCA.logLevel (function (level) {\n // ...\n }); ", "language": "javascript" } ] } [/block] ###Set log level [block:code] { "codes": [ { "code": " // var level = \"info\" | \"debug\" | \"trace\" | \"warning\" | \"error\" | \"off\"\n MOCA.setLogLevel (level, function () {\n // ...\n }); ", "language": "javascript" } ] } [/block] ###Login user: [block:callout] { "type": "warning", "title": "Login the user with every app startup", "body": "After launching the app, check whether the user is still logged in or not. If the user is still logged in, perform a new 'MOCA login'" } [/block] [block:code] { "codes": [ { "code": "MOCA.login (userId, function () {\n\t// ...\n}); ", "language": "javascript" } ] } [/block] ###Logout current user: [block:code] { "codes": [ { "code": " MOCA.logout (function () {\n // ...\n }); ", "language": "javascript" } ] } [/block] ###Check if user has been logged in: [block:code] { "codes": [ { "code": " MOCA.userLoggedIn (function (isLoggedIn) {\n if (isLoggedIn) {\n // ...\n } else {\n // ...\n }\n }); \n", "language": "javascript" } ] } [/block] ###Perform asynchronous fetch of beacons/campaigns data from cloud: [block:code] { "codes": [ { "code": " MOCA.performFetch (function (data) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get custom property by key: [block:code] { "codes": [ { "code": "\n MOCA.customProperty (key, function (dictionary) {\n // ...dictionary -> {\"requestedProperty\": \"value\"} or {} if not found\n }); \n", "language": "javascript" } ] } [/block] ###Set custom property (key/value): [block:code] { "codes": [ { "code": "\n MOCA.setCustomProperty (key, value, function () {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get MOCA instance unique ID: [block:code] { "codes": [ { "code": "\n MOCAInstance.identifier (function (iid) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get app session number: [block:code] { "codes": [ { "code": "\n MOCAInstance.session (function (sessionNumber) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get device push token [block:code] { "codes": [ { "code": " MOCAInstance.deviceToken (function (token) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get place device is currently visiting - It returns an array with the place(s) you are currently visiting - Combine this call with the `addEnterPlaceListener` callback to ensure you detect places correctly. [block:code] { "codes": [ { "code": " MOCA.placesInside(function (e) {\n console.log(\"places inside: \");\n console.log(e);\n});\n", "language": "javascript" } ] } [/block]
###Print MOCA SDK version [block:code] { "codes": [ { "code": " MOCA.version (function (version) {\n // ...\n });", "language": "javascript" } ] } [/block] ###Get MOCA app key: [block:code] { "codes": [ { "code": "\n MOCA.appKey (function (key) {\n // ...\n });\n", "language": "javascript" } ] } [/block] ###Get MOCA app secret: [block:code] { "codes": [ { "code": "\n MOCA.appSecret (function (secret) {\n // ...\n });\n", "language": "javascript" } ] } [/block] ###Check if MOCA was initialized: [block:code] { "codes": [ { "code": " if (MOCA.initialized(function (isInited)) {\n if (isInited) {\n // ...\n } else {\n // ...\n }\n }", "language": "javascript" } ] } [/block] ###Check if MOCA proximity is enabled: [block:code] { "codes": [ { "code": " if (MOCA.proximityEnabled(function (enabled)) {\n if (enabled) {\n // ...\n } else {\n // ...\n }\n }\n", "language": "javascript" } ] } [/block] ###Enable MOCA proximity: [block:code] { "codes": [ { "code": "MOCA.setProximityEnabled(true, function () {\n\t// ...\n});", "language": "javascript" } ] } [/block] ###Get log level: [block:code] { "codes": [ { "code": " MOCA.logLevel (function (level) {\n // ...\n }); ", "language": "javascript" } ] } [/block] ###Set log level [block:code] { "codes": [ { "code": " // var level = \"info\" | \"debug\" | \"trace\" | \"warning\" | \"error\" | \"off\"\n MOCA.setLogLevel (level, function () {\n // ...\n }); ", "language": "javascript" } ] } [/block] ###Login user: [block:callout] { "type": "warning", "title": "Login the user with every app startup", "body": "After launching the app, check whether the user is still logged in or not. If the user is still logged in, perform a new 'MOCA login'" } [/block] [block:code] { "codes": [ { "code": "MOCA.login (userId, function () {\n\t// ...\n}); ", "language": "javascript" } ] } [/block] ###Logout current user: [block:code] { "codes": [ { "code": " MOCA.logout (function () {\n // ...\n }); ", "language": "javascript" } ] } [/block] ###Check if user has been logged in: [block:code] { "codes": [ { "code": " MOCA.userLoggedIn (function (isLoggedIn) {\n if (isLoggedIn) {\n // ...\n } else {\n // ...\n }\n }); \n", "language": "javascript" } ] } [/block] ###Perform asynchronous fetch of beacons/campaigns data from cloud: [block:code] { "codes": [ { "code": " MOCA.performFetch (function (data) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get custom property by key: [block:code] { "codes": [ { "code": "\n MOCA.customProperty (key, function (dictionary) {\n // ...dictionary -> {\"requestedProperty\": \"value\"} or {} if not found\n }); \n", "language": "javascript" } ] } [/block] ###Set custom property (key/value): [block:code] { "codes": [ { "code": "\n MOCA.setCustomProperty (key, value, function () {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get MOCA instance unique ID: [block:code] { "codes": [ { "code": "\n MOCAInstance.identifier (function (iid) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get app session number: [block:code] { "codes": [ { "code": "\n MOCAInstance.session (function (sessionNumber) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get device push token [block:code] { "codes": [ { "code": " MOCAInstance.deviceToken (function (token) {\n // ...\n }); \n", "language": "javascript" } ] } [/block] ###Get place device is currently visiting - It returns an array with the place(s) you are currently visiting - Combine this call with the `addEnterPlaceListener` callback to ensure you detect places correctly. [block:code] { "codes": [ { "code": " MOCA.placesInside(function (e) {\n console.log(\"places inside: \");\n console.log(e);\n});\n", "language": "javascript" } ] } [/block]
{"_id":"5f998577fb81e800451c030e","hidden":false,"next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","slug":"javascript-moca-constants","user":"55a61860249a40190051d941","version":"5f998577fb81e800451c032f","__v":0,"createdAt":"2015-12-30T14:27:57.235Z","parentDoc":null,"type":"basic","updates":[],"isReference":false,"link_external":false,"order":1,"sync_unique":"","title":"Javascript MOCA Constants","body":"[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var MOCA = function () {\\n    // CONSTANTS\\n    // Events\\n    this.DID_ENTER_RANGE = \\\"enterBeacon\\\";\\n    this.DID_EXIT_RANGE = \\\"exitBeacon\\\";\\n    this.BEACON_PROXIMITY_CHANGE = \\\"beaconProximityChange\\\";\\n    this.DID_ENTER_PLACE = \\\"enterPlace\\\";\\n    this.DID_EXIT_PLACE = \\\"exitPlace\\\";\\n    this.DID_ENTER_ZONE = \\\"enterZone\\\";\\n    this.DID_EXIT_ZONE = \\\"exitZone\\\";\\n\\n    // Actions\\n    this.DISPLAY_ALERT = \\\"displayAlert\\\";\\n    this.OPEN_URL = \\\"openUrl\\\";\\n    this.SHOW_EMBEDDED_HTML = \\\"showEmbeddedHtml\\\";\\n    this.PLAY_VIDEO_FROM_URL = \\\"playVideo\\\";\\n    this.IMAGE_FROM_URL = \\\"showImage\\\";\\n    this.PASSBOOK_FROM_URL = \\\"addPassbook\\\";\\n    this.ADD_TAG = \\\"addTag\\\";\\n    this.PLAY_NOTIFICATION_SOUND = \\\"playSound\\\";\\n    this.PERFORM_CUSTOM_ACTION = \\\"customAction\\\";\\n\\n    // Other\\n    this.DID_LOADED_BEACONS_DATA = \\\"didLoadedBeaconsData\\\";\\n    \\n    this.APP_KEY = \\\"moca_app_key\\\";\\n    this.APP_SECRET = \\\"moca_app_secret\\\";\\n\\n    this.GCM_SENDER_ID = \\\"gcm_sender_id\\\";\\n};\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","excerpt":"","githubsync":"","link_url":"","api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"category":"5f998576fb81e800451c02f8","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Javascript MOCA Constants


[block:code] { "codes": [ { "code": "var MOCA = function () {\n // CONSTANTS\n // Events\n this.DID_ENTER_RANGE = \"enterBeacon\";\n this.DID_EXIT_RANGE = \"exitBeacon\";\n this.BEACON_PROXIMITY_CHANGE = \"beaconProximityChange\";\n this.DID_ENTER_PLACE = \"enterPlace\";\n this.DID_EXIT_PLACE = \"exitPlace\";\n this.DID_ENTER_ZONE = \"enterZone\";\n this.DID_EXIT_ZONE = \"exitZone\";\n\n // Actions\n this.DISPLAY_ALERT = \"displayAlert\";\n this.OPEN_URL = \"openUrl\";\n this.SHOW_EMBEDDED_HTML = \"showEmbeddedHtml\";\n this.PLAY_VIDEO_FROM_URL = \"playVideo\";\n this.IMAGE_FROM_URL = \"showImage\";\n this.PASSBOOK_FROM_URL = \"addPassbook\";\n this.ADD_TAG = \"addTag\";\n this.PLAY_NOTIFICATION_SOUND = \"playSound\";\n this.PERFORM_CUSTOM_ACTION = \"customAction\";\n\n // Other\n this.DID_LOADED_BEACONS_DATA = \"didLoadedBeaconsData\";\n \n this.APP_KEY = \"moca_app_key\";\n this.APP_SECRET = \"moca_app_secret\";\n\n this.GCM_SENDER_ID = \"gcm_sender_id\";\n};", "language": "javascript" } ] } [/block]
[block:code] { "codes": [ { "code": "var MOCA = function () {\n // CONSTANTS\n // Events\n this.DID_ENTER_RANGE = \"enterBeacon\";\n this.DID_EXIT_RANGE = \"exitBeacon\";\n this.BEACON_PROXIMITY_CHANGE = \"beaconProximityChange\";\n this.DID_ENTER_PLACE = \"enterPlace\";\n this.DID_EXIT_PLACE = \"exitPlace\";\n this.DID_ENTER_ZONE = \"enterZone\";\n this.DID_EXIT_ZONE = \"exitZone\";\n\n // Actions\n this.DISPLAY_ALERT = \"displayAlert\";\n this.OPEN_URL = \"openUrl\";\n this.SHOW_EMBEDDED_HTML = \"showEmbeddedHtml\";\n this.PLAY_VIDEO_FROM_URL = \"playVideo\";\n this.IMAGE_FROM_URL = \"showImage\";\n this.PASSBOOK_FROM_URL = \"addPassbook\";\n this.ADD_TAG = \"addTag\";\n this.PLAY_NOTIFICATION_SOUND = \"playSound\";\n this.PERFORM_CUSTOM_ACTION = \"customAction\";\n\n // Other\n this.DID_LOADED_BEACONS_DATA = \"didLoadedBeaconsData\";\n \n this.APP_KEY = \"moca_app_key\";\n this.APP_SECRET = \"moca_app_secret\";\n\n this.GCM_SENDER_ID = \"gcm_sender_id\";\n};", "language": "javascript" } ] } [/block]
{"_id":"5f998577fb81e800451c030f","user":"559a618bdbcfd20d00710b38","body":"##Returning objects\n\nEach method can return a `beacon`, a `zone` or a `place`.\n\n####`beacon` object\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n\\t\\\"type\\\": \\\"beacon\\\",\\n\\t\\\"id\\\":\\\"xxx\\\",\\n\\t\\\"uuid\\\":\\\"xxxxxxxxxxxx-xxxx-xxxx-xxxx\\\",\\n\\t\\\"major\\\": xxxxx,\\n  \\\"minor\\\": xxxxx,\\n\\t\\\"name\\\":\\\"beacon_name\\\",\\n  \\\"proximity\\\":\\\"immediate\\\" | \\\"near\\\" | \\\"far\\\" | \\\"unknown\\\",\\n  \\\"timestamp\\\": xxxxxxxx\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n####`zone` object\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n\\t\\\"type\\\":\\\"place\\\",\\n  \\\"id\\\":\\\"xxxx\\\",\\n  \\\"name\\\":\\\"xxxxx\\\",\\n\\t\\\"timestamp\\\": xxxxxxx,\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n####`place` object\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n\\t\\\"type\\\": \\\"place\\\",\\n\\t\\\"id\\\":\\\"xxx\\\",\\n \\t\\\"name\\\":\\\"place_name\\\",\\n\\t\\\"uuid\\\":\\\"xxxxxxxxxxxx-xxxx-xxxx-xxxx\\\",\\n\\tgeofence: {\\n  \\t\\\"lat\\\": xx.xxxxx,\\n\\t\\t\\\"long\\\": xx.xxxx,\\n    \\\"accuracy\\\":xx,\\n  }\\n  \\\"timestamp\\\": xxxxxxxx\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle MOCA data ready event\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addDataReadyListener (function (e) {\\n     // e.detail.beacons -- array of beacon objects. \\n  }); \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nThis method invoked when a proximity service loaded or updated a registry of beacons from MOCA cloud or from local cache.\n\n###Handle enter beacon range event:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addEnterBeaconListener (function (e) {\\n     // e.detail -> beacon object\\n  }); \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle exit beacon range event:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addExitBeaconListener (function (e) {\\n     // e.detail -> beacon object\\n  }); \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Method triggered when the state of a beacon proximity did changed:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addBeaconProximityChangeListener (function (e) {\\n     // e.detail  proximity change details (previous proximity\\n    // current proximity, beacon object)\\n  }); \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle enter place event:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addEnterPlaceListener (function (e) {\\n     // e.detail -> Place object\\n  }); \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle exit place event:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addExitPlaceListener (function (e) {\\n     // e.detail -> Place object\\n  }); \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle enter zone event:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addEnterZoneListener (function (e) {\\n     // e.detail -> Zone object\\n  }); \",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle exit zone event:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  MOCA.addExitZoneListener (function (e) {\\n     // e.detail -> Zone object\\n  }); \\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","createdAt":"2015-07-31T09:59:32.294Z","link_url":"","next":{"pages":[],"description":""},"order":2,"project":"559a61d2dbcfd20d00710b39","type":"basic","sync_unique":"","__v":0,"api":{"results":{"codes":[{"status":200,"name":"","code":"{}","language":"json"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","hidden":false,"isReference":false,"link_external":false,"slug":"javascript-api-usage-1","version":"5f998577fb81e800451c032f","category":"5f998576fb81e800451c02f8","githubsync":"","parentDoc":null,"title":"JavaScript Trigger Events","updates":[],"metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

JavaScript Trigger Events


##Returning objects Each method can return a `beacon`, a `zone` or a `place`. ####`beacon` object [block:code] { "codes": [ { "code": "{\n\t\"type\": \"beacon\",\n\t\"id\":\"xxx\",\n\t\"uuid\":\"xxxxxxxxxxxx-xxxx-xxxx-xxxx\",\n\t\"major\": xxxxx,\n \"minor\": xxxxx,\n\t\"name\":\"beacon_name\",\n \"proximity\":\"immediate\" | \"near\" | \"far\" | \"unknown\",\n \"timestamp\": xxxxxxxx\n}", "language": "javascript" } ] } [/block] ####`zone` object [block:code] { "codes": [ { "code": "{\n\t\"type\":\"place\",\n \"id\":\"xxxx\",\n \"name\":\"xxxxx\",\n\t\"timestamp\": xxxxxxx,\n}", "language": "javascript" } ] } [/block] ####`place` object [block:code] { "codes": [ { "code": "{\n\t\"type\": \"place\",\n\t\"id\":\"xxx\",\n \t\"name\":\"place_name\",\n\t\"uuid\":\"xxxxxxxxxxxx-xxxx-xxxx-xxxx\",\n\tgeofence: {\n \t\"lat\": xx.xxxxx,\n\t\t\"long\": xx.xxxx,\n \"accuracy\":xx,\n }\n \"timestamp\": xxxxxxxx\n}", "language": "javascript" } ] } [/block] ###Handle MOCA data ready event [block:code] { "codes": [ { "code": " MOCA.addDataReadyListener (function (e) {\n // e.detail.beacons -- array of beacon objects. \n }); \n", "language": "javascript" } ] } [/block] This method invoked when a proximity service loaded or updated a registry of beacons from MOCA cloud or from local cache. ###Handle enter beacon range event: [block:code] { "codes": [ { "code": " MOCA.addEnterBeaconListener (function (e) {\n // e.detail -> beacon object\n }); \n", "language": "javascript" } ] } [/block] ###Handle exit beacon range event: [block:code] { "codes": [ { "code": " MOCA.addExitBeaconListener (function (e) {\n // e.detail -> beacon object\n }); \n", "language": "javascript" } ] } [/block] ###Method triggered when the state of a beacon proximity did changed: [block:code] { "codes": [ { "code": " MOCA.addBeaconProximityChangeListener (function (e) {\n // e.detail proximity change details (previous proximity\n // current proximity, beacon object)\n }); \n", "language": "javascript" } ] } [/block] ###Handle enter place event: [block:code] { "codes": [ { "code": " MOCA.addEnterPlaceListener (function (e) {\n // e.detail -> Place object\n }); ", "language": "javascript" } ] } [/block] ###Handle exit place event: [block:code] { "codes": [ { "code": " MOCA.addExitPlaceListener (function (e) {\n // e.detail -> Place object\n }); ", "language": "javascript" } ] } [/block] ###Handle enter zone event: [block:code] { "codes": [ { "code": " MOCA.addEnterZoneListener (function (e) {\n // e.detail -> Zone object\n }); ", "language": "javascript" } ] } [/block] ###Handle exit zone event: [block:code] { "codes": [ { "code": " MOCA.addExitZoneListener (function (e) {\n // e.detail -> Zone object\n }); \n", "language": "javascript" } ] } [/block]
##Returning objects Each method can return a `beacon`, a `zone` or a `place`. ####`beacon` object [block:code] { "codes": [ { "code": "{\n\t\"type\": \"beacon\",\n\t\"id\":\"xxx\",\n\t\"uuid\":\"xxxxxxxxxxxx-xxxx-xxxx-xxxx\",\n\t\"major\": xxxxx,\n \"minor\": xxxxx,\n\t\"name\":\"beacon_name\",\n \"proximity\":\"immediate\" | \"near\" | \"far\" | \"unknown\",\n \"timestamp\": xxxxxxxx\n}", "language": "javascript" } ] } [/block] ####`zone` object [block:code] { "codes": [ { "code": "{\n\t\"type\":\"place\",\n \"id\":\"xxxx\",\n \"name\":\"xxxxx\",\n\t\"timestamp\": xxxxxxx,\n}", "language": "javascript" } ] } [/block] ####`place` object [block:code] { "codes": [ { "code": "{\n\t\"type\": \"place\",\n\t\"id\":\"xxx\",\n \t\"name\":\"place_name\",\n\t\"uuid\":\"xxxxxxxxxxxx-xxxx-xxxx-xxxx\",\n\tgeofence: {\n \t\"lat\": xx.xxxxx,\n\t\t\"long\": xx.xxxx,\n \"accuracy\":xx,\n }\n \"timestamp\": xxxxxxxx\n}", "language": "javascript" } ] } [/block] ###Handle MOCA data ready event [block:code] { "codes": [ { "code": " MOCA.addDataReadyListener (function (e) {\n // e.detail.beacons -- array of beacon objects. \n }); \n", "language": "javascript" } ] } [/block] This method invoked when a proximity service loaded or updated a registry of beacons from MOCA cloud or from local cache. ###Handle enter beacon range event: [block:code] { "codes": [ { "code": " MOCA.addEnterBeaconListener (function (e) {\n // e.detail -> beacon object\n }); \n", "language": "javascript" } ] } [/block] ###Handle exit beacon range event: [block:code] { "codes": [ { "code": " MOCA.addExitBeaconListener (function (e) {\n // e.detail -> beacon object\n }); \n", "language": "javascript" } ] } [/block] ###Method triggered when the state of a beacon proximity did changed: [block:code] { "codes": [ { "code": " MOCA.addBeaconProximityChangeListener (function (e) {\n // e.detail proximity change details (previous proximity\n // current proximity, beacon object)\n }); \n", "language": "javascript" } ] } [/block] ###Handle enter place event: [block:code] { "codes": [ { "code": " MOCA.addEnterPlaceListener (function (e) {\n // e.detail -> Place object\n }); ", "language": "javascript" } ] } [/block] ###Handle exit place event: [block:code] { "codes": [ { "code": " MOCA.addExitPlaceListener (function (e) {\n // e.detail -> Place object\n }); ", "language": "javascript" } ] } [/block] ###Handle enter zone event: [block:code] { "codes": [ { "code": " MOCA.addEnterZoneListener (function (e) {\n // e.detail -> Zone object\n }); ", "language": "javascript" } ] } [/block] ###Handle exit zone event: [block:code] { "codes": [ { "code": " MOCA.addExitZoneListener (function (e) {\n // e.detail -> Zone object\n }); \n", "language": "javascript" } ] } [/block]
{"_id":"5f998577fb81e800451c0310","__v":0,"version":"5f998577fb81e800451c032f","createdAt":"2015-12-30T12:08:15.390Z","githubsync":"","order":3,"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","updates":[],"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required","params":[],"url":""},"body":"###Action Object\n \nAll action callbacks return the Action Object with the same format. The available action names can be found in \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  \\\"detail\\\": {\\n    \\\"action_name\\\": \\\"action_message\\\"\\n  }\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\n###Handle Custom Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a custom action is invoked.\\n//\\nMOCA.addCustomActionListener (function (e) {\\n\\te.detail.customAction; // string with custom action\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Simple Message Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a message action is invoked.\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No message will be shown)\\n//\\nMOCA.addDisplayAlertListener (false, function (e) {\\n\\te.detail.displayAlert // String with Message to show\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Open URL Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when an \\\"open url\\\" action is invoked.\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No webview will be shown)\\n//\\nMOCA.addOpenUrlListener (false, function (e) {\\n\\te.detail.openUrl // String with URL\\n});\\n//\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Show HTML Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when an embedded html action is invoked.\\n//\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No webview will be shown)\\n//\\nMOCA.addShowEmbeddedHtmlListener (false, function (e) {\\n\\te.detail.showEmbeddedHtml // String with embedded HTML\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Video Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a video action is invoked.\\n//\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No video will be played)\\n//\\nMOCA.addPlayVideoListener (false, function (e) {\\n\\te.detail.playVideo // String with video URL\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Image Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a image action is invoked.\\n//\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No image will be shown)\\n//\\nMOCA.addShowImageListener (false, function (e) {\\n\\te.detail.showImage // String with Image URL\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Passbook Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a passbook action is invoked.\\n//\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No passbook will be shown)\\n//\\nMOCA.addAddPassbookListener (false, function (e) {\\n\\te.detail.addPassbook // String with Passbook URL\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Tag Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a tag action is invoked.\\n//\\nMOCA.addAddTagListener (function (e) {\\n\\te.detail.addTag // JSONObject with tagName and tagValue\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n###Handle Sound Action\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//\\n// Method invoked when a sound action is invoked.\\n//\\n//\\n// args: (false, callback) to allow MOCA to show the experience.\\n//       (true, callback) to prevent MOCA from showing the experience. (No sound will be played)\\n//\\nMOCA.addPlaySoundListener (false, function (e) {\\n\\te.detail.playSound // String with sound path\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","category":"5f998576fb81e800451c02f8","isReference":false,"link_external":false,"title":"Javascript Action Events","excerpt":"","hidden":false,"link_url":"","next":{"pages":[],"description":""},"slug":"javascript-action-events","sync_unique":"","type":"basic","user":"55a61860249a40190051d941","metadata":{"title":"","description":"","image":[]},"childrenPages":[]}

Javascript Action Events


###Action Object All action callbacks return the Action Object with the same format. The available action names can be found in [block:code] { "codes": [ { "code": "{\n \"detail\": {\n \"action_name\": \"action_message\"\n }\n}", "language": "json" } ] } [/block] ###Handle Custom Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a custom action is invoked.\n//\nMOCA.addCustomActionListener (function (e) {\n\te.detail.customAction; // string with custom action\n});", "language": "javascript" } ] } [/block] ###Handle Simple Message Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a message action is invoked.\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No message will be shown)\n//\nMOCA.addDisplayAlertListener (false, function (e) {\n\te.detail.displayAlert // String with Message to show\n});", "language": "javascript" } ] } [/block] ###Handle Open URL Action [block:code] { "codes": [ { "code": "//\n// Method invoked when an \"open url\" action is invoked.\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No webview will be shown)\n//\nMOCA.addOpenUrlListener (false, function (e) {\n\te.detail.openUrl // String with URL\n});\n//", "language": "javascript" } ] } [/block] ###Handle Show HTML Action [block:code] { "codes": [ { "code": "//\n// Method invoked when an embedded html action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No webview will be shown)\n//\nMOCA.addShowEmbeddedHtmlListener (false, function (e) {\n\te.detail.showEmbeddedHtml // String with embedded HTML\n});", "language": "javascript" } ] } [/block] ###Handle Video Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a video action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No video will be played)\n//\nMOCA.addPlayVideoListener (false, function (e) {\n\te.detail.playVideo // String with video URL\n});", "language": "javascript" } ] } [/block] ###Handle Image Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a image action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No image will be shown)\n//\nMOCA.addShowImageListener (false, function (e) {\n\te.detail.showImage // String with Image URL\n});", "language": "javascript" } ] } [/block] ###Handle Passbook Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a passbook action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No passbook will be shown)\n//\nMOCA.addAddPassbookListener (false, function (e) {\n\te.detail.addPassbook // String with Passbook URL\n});", "language": "javascript" } ] } [/block] ###Handle Tag Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a tag action is invoked.\n//\nMOCA.addAddTagListener (function (e) {\n\te.detail.addTag // JSONObject with tagName and tagValue\n});", "language": "javascript" } ] } [/block] ###Handle Sound Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a sound action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No sound will be played)\n//\nMOCA.addPlaySoundListener (false, function (e) {\n\te.detail.playSound // String with sound path\n});", "language": "javascript" } ] } [/block]
###Action Object All action callbacks return the Action Object with the same format. The available action names can be found in [block:code] { "codes": [ { "code": "{\n \"detail\": {\n \"action_name\": \"action_message\"\n }\n}", "language": "json" } ] } [/block] ###Handle Custom Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a custom action is invoked.\n//\nMOCA.addCustomActionListener (function (e) {\n\te.detail.customAction; // string with custom action\n});", "language": "javascript" } ] } [/block] ###Handle Simple Message Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a message action is invoked.\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No message will be shown)\n//\nMOCA.addDisplayAlertListener (false, function (e) {\n\te.detail.displayAlert // String with Message to show\n});", "language": "javascript" } ] } [/block] ###Handle Open URL Action [block:code] { "codes": [ { "code": "//\n// Method invoked when an \"open url\" action is invoked.\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No webview will be shown)\n//\nMOCA.addOpenUrlListener (false, function (e) {\n\te.detail.openUrl // String with URL\n});\n//", "language": "javascript" } ] } [/block] ###Handle Show HTML Action [block:code] { "codes": [ { "code": "//\n// Method invoked when an embedded html action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No webview will be shown)\n//\nMOCA.addShowEmbeddedHtmlListener (false, function (e) {\n\te.detail.showEmbeddedHtml // String with embedded HTML\n});", "language": "javascript" } ] } [/block] ###Handle Video Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a video action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No video will be played)\n//\nMOCA.addPlayVideoListener (false, function (e) {\n\te.detail.playVideo // String with video URL\n});", "language": "javascript" } ] } [/block] ###Handle Image Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a image action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No image will be shown)\n//\nMOCA.addShowImageListener (false, function (e) {\n\te.detail.showImage // String with Image URL\n});", "language": "javascript" } ] } [/block] ###Handle Passbook Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a passbook action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No passbook will be shown)\n//\nMOCA.addAddPassbookListener (false, function (e) {\n\te.detail.addPassbook // String with Passbook URL\n});", "language": "javascript" } ] } [/block] ###Handle Tag Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a tag action is invoked.\n//\nMOCA.addAddTagListener (function (e) {\n\te.detail.addTag // JSONObject with tagName and tagValue\n});", "language": "javascript" } ] } [/block] ###Handle Sound Action [block:code] { "codes": [ { "code": "//\n// Method invoked when a sound action is invoked.\n//\n//\n// args: (false, callback) to allow MOCA to show the experience.\n// (true, callback) to prevent MOCA from showing the experience. (No sound will be played)\n//\nMOCA.addPlaySoundListener (false, function (e) {\n\te.detail.playSound // String with sound path\n});", "language": "javascript" } ] } [/block]