{"_id":"59198f20eba9ac31000185f2","__v":0,"hidden":false,"order":0,"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":"59198f20eba9ac31000185e0","githubsync":"","link_url":"","version":"59198f1eeba9ac31000185de","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":"You may install the MOCA SDK using **CocoaPods** or **manually**. For both installation methods the minimum supported iOS version is 8. Installing in a project with iOS 7 compatibility (or lower) will cause errors.\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'\nend\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](http://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: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 7.\n3. The SDK requires `9.x` or later.\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   - `CoreBluetooth.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","childrenPages":[]}

Installation

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

You may install the MOCA SDK using **CocoaPods** or **manually**. For both installation methods the minimum supported iOS version is 8. Installing in a project with iOS 7 compatibility (or lower) will cause errors. [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' end ``` 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](http://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: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 7. 3. The SDK requires `9.x` or later. 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` - `CoreBluetooth.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]
You may install the MOCA SDK using **CocoaPods** or **manually**. For both installation methods the minimum supported iOS version is 8. Installing in a project with iOS 7 compatibility (or lower) will cause errors. [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' end ``` 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](http://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: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 7. 3. The SDK requires `9.x` or later. 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` - `CoreBluetooth.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":"59198f20eba9ac31000185f3","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":"59198f1eeba9ac31000185de","body":"To start using MOCA SDK in your app, you’ll need to configure it first.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Location Services\"\n}\n[/block]\nTo detect beacons, geofences and track significant changes in user location, the SDK uses *iOS Location Services*. Starting with iOS 11, you will need to explain to the user the usage of each type of permissions.\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###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###Bluetooth Usage Description\n\nStarting with **iOS 10**, Apple requires this mode to be added to all applications that use the `CoreBluetooth` framework.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/02648cb-BTUsage.png\",\n        \"BTUsage.png\",\n        706,\n        21,\n        \"#5e3d2b\"\n      ]\n    }\n  ]\n}\n[/block]\nEquivalent version using raw key / values:\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/d05e962-BTUsageKeyValue.png\",\n        \"BTUsageKeyValue.png\",\n        700,\n        22,\n        \"#5b3728\"\n      ]\n    }\n  ]\n}\n[/block]\n\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   - Optionally, you may want to enable Remote notifications in your app.\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* If you don't have your account, you are invited to [Sign Up Free] (http://mocaplatform.com/signup). \n* Select Apps item at left sidebar, and then click <i>+ New App</i> in the content panel. Fill in the form and complete the app creation.\n* Select if your app is *In Development* or *In Production* mode.\n* Open newly created app and 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: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    \"7-0\": \"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]\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]","githubsync":"","hidden":false,"link_external":false,"next":{"pages":[],"description":""},"sync_unique":"","title":"Configuration","type":"basic","category":"59198f20eba9ac31000185e0","excerpt":"This section describes how to configure MOCA iOS SDK in your app.","isReference":false,"order":1,"slug":"moca-ios-sdk-configuration","updates":[],"childrenPages":[]}

Configuration

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

To start using MOCA SDK in your app, you’ll need to configure it first. [block:api-header] { "type": "basic", "title": "Location Services" } [/block] To detect beacons, geofences and track significant changes in user location, the SDK uses *iOS Location Services*. Starting with iOS 11, you will need to explain to the user the usage of each type of permissions. | **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] ###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] ###Bluetooth Usage Description Starting with **iOS 10**, Apple requires this mode to be added to all applications that use the `CoreBluetooth` framework. [block:image] { "images": [ { "image": [ "https://files.readme.io/02648cb-BTUsage.png", "BTUsage.png", 706, 21, "#5e3d2b" ] } ] } [/block] Equivalent version using raw key / values: [block:image] { "images": [ { "image": [ "https://files.readme.io/d05e962-BTUsageKeyValue.png", "BTUsageKeyValue.png", 700, 22, "#5b3728" ] } ] } [/block] [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 - Optionally, you may want to enable Remote notifications in your app. [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. * If you don't have your account, you are invited to [Sign Up Free] (http://mocaplatform.com/signup). * Select Apps item at left sidebar, and then click <i>+ New App</i> in the content panel. Fill in the form and complete the app creation. * Select if your app is *In Development* or *In Production* mode. * Open newly created app and 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: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.", "7-0": "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] [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]
To start using MOCA SDK in your app, you’ll need to configure it first. [block:api-header] { "type": "basic", "title": "Location Services" } [/block] To detect beacons, geofences and track significant changes in user location, the SDK uses *iOS Location Services*. Starting with iOS 11, you will need to explain to the user the usage of each type of permissions. | **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] ###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] ###Bluetooth Usage Description Starting with **iOS 10**, Apple requires this mode to be added to all applications that use the `CoreBluetooth` framework. [block:image] { "images": [ { "image": [ "https://files.readme.io/02648cb-BTUsage.png", "BTUsage.png", 706, 21, "#5e3d2b" ] } ] } [/block] Equivalent version using raw key / values: [block:image] { "images": [ { "image": [ "https://files.readme.io/d05e962-BTUsageKeyValue.png", "BTUsageKeyValue.png", 700, 22, "#5b3728" ] } ] } [/block] [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 - Optionally, you may want to enable Remote notifications in your app. [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. * If you don't have your account, you are invited to [Sign Up Free] (http://mocaplatform.com/signup). * Select Apps item at left sidebar, and then click <i>+ New App</i> in the content panel. Fill in the form and complete the app creation. * Select if your app is *In Development* or *In Production* mode. * Open newly created app and 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: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.", "7-0": "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] [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]
{"_id":"59198f20eba9ac31000185f4","title":"Integration","order":2,"slug":"moca-ios-sdk-integration","parentDoc":null,"version":"59198f1eeba9ac31000185de","__v":0,"excerpt":"This section describes how to integrate MOCA iOS SDK with your app code.","category":"59198f20eba9ac31000185e0","githubsync":"","isReference":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","type":"basic","body":"1 - Import `<MOCA/MOCA.h>` header file into your app’s delegate implementation file. (Only in Objective-C, for Swift projects, you do not need any `import` statements).\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: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\\n    let mocaStarted = MOCA.initializeSDK()\\n    if !mocaStarted {\\n        NSLog(\\\"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\": \"    // 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    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    // 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    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 - If you use MOCA Remote Push notifications, integrate the following code in your `AppDelegate` (recommended):\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\": \"\\t\\tfunc 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        \\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\": \"warning\",\n  \"title\": \"UILocalNotification API (Deprecated)\",\n  \"body\": \"If your application still makes use of the deprecated API UILocalNotification, **do not** integrate using the code sample in the points 3.1, 3.2 and 3.3. Instead use the following code in your `AppDelegate`\\n\\nIf you use the `UNNotificationCenter` API, the `UILocalNotification` methods **won't work anymore.**\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//UILocalNotification API has been deprecated. Use the following code only for compatibility issues with your current implementation or 3rd party libraries.\\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\\n{\\n    if (MOCA.initialized) {\\n        [MOCA handleLocalNotification:notification];\\n    }\\n}\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"func application(_ application: UIApplication, didReceive notification: UILocalNotification) {\\n    if MOCA.initialized() {\\n        MOCA.handle(notification)\\n    }\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Important considerations: Power Consumption\"\n}\n[/block]\n&nbsp;\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/r4ZqBpdYSWK7mLtjejr1_moca-low-battery.png\",\n        \"moca-low-battery.png\",\n        \"200\",\n        \"95\",\n        \"#fc4464\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n&nbsp;\nWhen backgrounded, your application will be woken up by iOS in order to respond to location events. That means that the `didFinishLaunchingWithOptions` **could be called several times** while the user is moving, or when the device is in the range of bluetooth beacons.\n**Be extra careful**: filter out these events so that MOCA SDK is initialized, but any other heavy tasks are not executed. If the `UIApplicationLaunchOptionsLocationKey` key is present in the `launchOptions`, you can tell that the App was launched to respond to a location event.\n\nExample:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#import <MOCA.h>\\n\\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\\n{\\n    [MOCA initializeSDK];\\n    //Filter out the events\\n    if([launchOptions objectForKey:@\\\"UIApplicationLaunchOptionsLocationKey\\\"]) {\\n    \\t\\treturn YES;\\n    }\\n  \\t//do heavy stuff afterwards\\n}\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\\n    \\n    MOCA.initializeSDK()\\n    //Filter out the events\\n    if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {\\n        return true\\n    }\\n  \\t//do heavy stuff afterwards\\n\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"success\",\n  \"body\": \"At this point, you already have a proximity-aware app! Go to the [MOCA Console](https://console.mocaplatform.com), create some campaigns and test your Proximity Experiences.\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"Beacon detection cannot be tested in the simulator, you will need a real device (iPhone 4s or newer).\",\n  \"title\": \"Simulator\",\n  \"sidebar\": true\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","childrenPages":[]}

Integration

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

1 - Import `<MOCA/MOCA.h>` header file into your app’s delegate implementation file. (Only in Objective-C, for Swift projects, you do not need any `import` statements). 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: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n let mocaStarted = MOCA.initializeSDK()\n if !mocaStarted {\n NSLog(\"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": " // 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 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 // 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 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 - If you use MOCA Remote Push notifications, integrate the following code in your `AppDelegate` (recommended): [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": "\t\tfunc 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 \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": "warning", "title": "UILocalNotification API (Deprecated)", "body": "If your application still makes use of the deprecated API UILocalNotification, **do not** integrate using the code sample in the points 3.1, 3.2 and 3.3. Instead use the following code in your `AppDelegate`\n\nIf you use the `UNNotificationCenter` API, the `UILocalNotification` methods **won't work anymore.**" } [/block] [block:code] { "codes": [ { "code": "//UILocalNotification API has been deprecated. Use the following code only for compatibility issues with your current implementation or 3rd party libraries.\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\n{\n if (MOCA.initialized) {\n [MOCA handleLocalNotification:notification];\n }\n}", "language": "objectivec" }, { "code": "func application(_ application: UIApplication, didReceive notification: UILocalNotification) {\n if MOCA.initialized() {\n MOCA.handle(notification)\n }\n}", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Important considerations: Power Consumption" } [/block] &nbsp; [block:image] { "images": [ { "image": [ "https://files.readme.io/r4ZqBpdYSWK7mLtjejr1_moca-low-battery.png", "moca-low-battery.png", "200", "95", "#fc4464", "" ] } ] } [/block] &nbsp; When backgrounded, your application will be woken up by iOS in order to respond to location events. That means that the `didFinishLaunchingWithOptions` **could be called several times** while the user is moving, or when the device is in the range of bluetooth beacons. **Be extra careful**: filter out these events so that MOCA SDK is initialized, but any other heavy tasks are not executed. If the `UIApplicationLaunchOptionsLocationKey` key is present in the `launchOptions`, you can tell that the App was launched to respond to a location event. Example: [block:code] { "codes": [ { "code": "#import <MOCA.h>\n\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n [MOCA initializeSDK];\n //Filter out the events\n if([launchOptions objectForKey:@\"UIApplicationLaunchOptionsLocationKey\"]) {\n \t\treturn YES;\n }\n \t//do heavy stuff afterwards\n}", "language": "objectivec" }, { "code": "func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n \n MOCA.initializeSDK()\n //Filter out the events\n if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {\n return true\n }\n \t//do heavy stuff afterwards\n\n}", "language": "swift" } ] } [/block] [block:callout] { "type": "success", "body": "At this point, you already have a proximity-aware app! Go to the [MOCA Console](https://console.mocaplatform.com), create some campaigns and test your Proximity Experiences." } [/block] [block:callout] { "type": "info", "body": "Beacon detection cannot be tested in the simulator, you will need a real device (iPhone 4s or newer).", "title": "Simulator", "sidebar": true } [/block]
1 - Import `<MOCA/MOCA.h>` header file into your app’s delegate implementation file. (Only in Objective-C, for Swift projects, you do not need any `import` statements). 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: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n let mocaStarted = MOCA.initializeSDK()\n if !mocaStarted {\n NSLog(\"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": " // 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 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 // 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 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 - If you use MOCA Remote Push notifications, integrate the following code in your `AppDelegate` (recommended): [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": "\t\tfunc 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 \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": "warning", "title": "UILocalNotification API (Deprecated)", "body": "If your application still makes use of the deprecated API UILocalNotification, **do not** integrate using the code sample in the points 3.1, 3.2 and 3.3. Instead use the following code in your `AppDelegate`\n\nIf you use the `UNNotificationCenter` API, the `UILocalNotification` methods **won't work anymore.**" } [/block] [block:code] { "codes": [ { "code": "//UILocalNotification API has been deprecated. Use the following code only for compatibility issues with your current implementation or 3rd party libraries.\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\n{\n if (MOCA.initialized) {\n [MOCA handleLocalNotification:notification];\n }\n}", "language": "objectivec" }, { "code": "func application(_ application: UIApplication, didReceive notification: UILocalNotification) {\n if MOCA.initialized() {\n MOCA.handle(notification)\n }\n}", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Important considerations: Power Consumption" } [/block] &nbsp; [block:image] { "images": [ { "image": [ "https://files.readme.io/r4ZqBpdYSWK7mLtjejr1_moca-low-battery.png", "moca-low-battery.png", "200", "95", "#fc4464", "" ] } ] } [/block] &nbsp; When backgrounded, your application will be woken up by iOS in order to respond to location events. That means that the `didFinishLaunchingWithOptions` **could be called several times** while the user is moving, or when the device is in the range of bluetooth beacons. **Be extra careful**: filter out these events so that MOCA SDK is initialized, but any other heavy tasks are not executed. If the `UIApplicationLaunchOptionsLocationKey` key is present in the `launchOptions`, you can tell that the App was launched to respond to a location event. Example: [block:code] { "codes": [ { "code": "#import <MOCA.h>\n\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n [MOCA initializeSDK];\n //Filter out the events\n if([launchOptions objectForKey:@\"UIApplicationLaunchOptionsLocationKey\"]) {\n \t\treturn YES;\n }\n \t//do heavy stuff afterwards\n}", "language": "objectivec" }, { "code": "func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n \n MOCA.initializeSDK()\n //Filter out the events\n if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {\n return true\n }\n \t//do heavy stuff afterwards\n\n}", "language": "swift" } ] } [/block] [block:callout] { "type": "success", "body": "At this point, you already have a proximity-aware app! Go to the [MOCA Console](https://console.mocaplatform.com), create some campaigns and test your Proximity Experiences." } [/block] [block:callout] { "type": "info", "body": "Beacon detection cannot be tested in the simulator, you will need a real device (iPhone 4s or newer).", "title": "Simulator", "sidebar": true } [/block]
{"_id":"59198f20eba9ac31000185f5","__v":0,"body":"iOS iBeacon issues\n- CLProximity Toggling - iOS 7.0 and 7.1 has a known issue related to beacon unexpected proximity changes. It may happen that your have your app and a beacon is detected at a certain proximity distance, for example \"Near”. Both beacon and your device do not move. And suddenly the beacon ranging callback from iOS notifies you that beacon proximity changed to \"Immediate\", and then it switched back to \"Near\" again. This may happen several times. \n- The reason for this behavior resides both in BLE signal interference and in iOS logic for averaging the RSSI signal strength and determining CLProximity range. The effect is that you observe sudden rapid toggles between proximity regions.\n- We are working on a next version of SDK that will filter received signals, remove outliers and lower the sensitivity on region changes in order to provide a smoother user experience.","createdAt":"2015-07-17T14:31:06.333Z","hidden":false,"order":3,"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","version":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e0","githubsync":"","parentDoc":null,"project":"559a61d2dbcfd20d00710b39","user":"559a618bdbcfd20d00710b38","link_external":false,"link_url":"","sync_unique":"","updates":[],"childrenPages":[]}

Known issues


iOS iBeacon issues - CLProximity Toggling - iOS 7.0 and 7.1 has a known issue related to beacon unexpected proximity changes. It may happen that your have your app and a beacon is detected at a certain proximity distance, for example "Near”. Both beacon and your device do not move. And suddenly the beacon ranging callback from iOS notifies you that beacon proximity changed to "Immediate", and then it switched back to "Near" again. This may happen several times. - The reason for this behavior resides both in BLE signal interference and in iOS logic for averaging the RSSI signal strength and determining CLProximity range. The effect is that you observe sudden rapid toggles between proximity regions. - We are working on a next version of SDK that will filter received signals, remove outliers and lower the sensitivity on region changes in order to provide a smoother user experience.
iOS iBeacon issues - CLProximity Toggling - iOS 7.0 and 7.1 has a known issue related to beacon unexpected proximity changes. It may happen that your have your app and a beacon is detected at a certain proximity distance, for example "Near”. Both beacon and your device do not move. And suddenly the beacon ranging callback from iOS notifies you that beacon proximity changed to "Immediate", and then it switched back to "Near" again. This may happen several times. - The reason for this behavior resides both in BLE signal interference and in iOS logic for averaging the RSSI signal strength and determining CLProximity range. The effect is that you observe sudden rapid toggles between proximity regions. - We are working on a next version of SDK that will filter received signals, remove outliers and lower the sensitivity on region changes in order to provide a smoother user experience.
{"_id":"59198f20eba9ac31000185f6","api":{"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[]},"link_url":"","sync_unique":"","title":"Integration Examples","next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","slug":"moca-ios-sdk-integration-examples","updates":[],"body":"The typical integration scenarios include handling of the following in-app events:\n* Launch app\n* User Login\n* User Logout\n* Receive Push Notification \n* Registered for Remote Push Notifications\n* Fetch Campaigns\n* Enter Screen\n* Custom Events\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Launch app\"\n}\n[/block]\nThis code sample shows how to initialize MOCA SDK on app startup and also handle situations when the app is started by opening a push notification. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\\n{\\n   // Init MOCA SDK\\n   [MOCA initializeSDK];\\n   if (launchOptions != nil) {\\n       // Launched from push notification\\n       NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];\\n       if (notification) {\\n           // Notify MOCA the app started from push\\n           [MOCA handleRemoteNotification:notification];\\n       }\\n   }\\n   // Optionally, set guest properties\\n   MOCAInstance * currentInstance = [MOCA currentInstance];\\n   if (currentInstance) {\\n        [currentInstance setValue:@\\\"property_1_value\\\" forProperty:@\\\"guest_property_1\\\"];\\n        [currentInstance setValue:@\\\"property_2_value\\\" forProperty:@\\\"guest_property_2\\\"];\\n        [currentInstance setValue:[NSNumber numberWithDouble:property3_value] forProperty:@\\\"guest_property_3\\\"];\\n     \\n        // Submit change to the cloud \\n        [currentInstance saveWithBlock:^(MOCAInstance *instance, NSError *error) {\\n            if (error) {\\n               NSLog(@\\\"Save instance failed: %@\\\", error);\\n            }\\n        }];\\n   }\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {\\n        // Init MOCA SDK\\n        MOCA.initializeSDK()\\n        if launchOptions != nil {\\n            // Launched from push notification\\n            let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] ?? [AnyHashable: Any]()\\n            if !notification.isEmpty {\\n                // Notify MOCA the app started from push\\n                MOCA.handleRemoteNotification(notification)\\n            }\\n        }\\n        let currentInstance: MOCAInstance? = MOCA.currentInstance()\\n        if currentInstance != nil {\\n            currentInstance?.setValue(\\\"property_1_value\\\", forProperty: \\\"guest_property_1\\\")\\n            currentInstance?.setValue(\\\"property_2_value\\\", forProperty: \\\"guest_property_1\\\")\\n            currentInstance?.setValue(2.9, forProperty: \\\"guest_property_3\\\")\\n            currentInstance?.save({ (instance: MOCAInstance?, error: Error?) in\\n                if (error != nil) {\\n                    print(\\\"Save instance failed: (%@)\\\", error ?? \\\"Error not available\\\")\\n                }\\n            })\\n        }\\n        return true\\n\\n    }\\n    \\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"User log-in\"\n}\n[/block]\nThis code sample shows how to inform MOCA that a user has logged into the app. This call should be executed each time the user performs the log in, even if the app persists user session on app close. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"   // Notify MOCA, the user logged in. Must be called after each app launch.\\n\\n   NSString * userId = ...\\n   MOCAUser *user = [[MOCA currentInstance] login:loginMgr.username];\\n   \\n   [user setValue:@”paidComplete\\\" forProperty:@\\\"paymentStatus\\\"];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"pictureStatus\\\"];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"merchantId\\\"];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"jobTitle\\\"];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"companyName\\\"];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"country\\\"];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"...\\\"];\\n        \\n   NSArray * arrValue = [NSArray arrayWithObjects: @\\\"Attr1\\\",@\\\"Attr2\\\",@\\\"Attr3\\\", nil];\\n   [user setValue:@\\\"...\\\" forProperty:@\\\"...\\\"];\\n    \\n   // Submit change to the cloud \\n   [user saveWithBlock:^(MOCAUser *user, NSError *error) {\\n      if (error) {\\n          NSLog(@\\\"Save user failed: %@\\\", error);\\n      }\\n   }];\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"        let userId: String = \\\"\\\"\\n        let user: MOCAUser? = MOCA.currentInstance().login(\\\"username\\\")\\n        user?.setValue(\\\"paidComplete\\\",forProperty: \\\"paymentStatus\\\")\\n        user?.setValue(\\\"...\\\",forProperty: \\\"pictureStatus\\\")\\n        user?.setValue(\\\"...\\\",forProperty: \\\"merchantId\\\")\\n        user?.setValue(\\\"...\\\",forProperty: \\\"jobTitle\\\")\\n        user?.setValue(\\\"...\\\",forProperty: \\\"companyName\\\")\\n        user?.setValue(\\\"...\\\",forProperty: \\\"country\\\")\\n        user?.setValue(\\\"...\\\",forProperty: \\\"...\\\")\\n        let arrValue: [Any] = [\\\"Attr1\\\", \\\"Attr2\\\", \\\"Attr3\\\"]\\n        user?.setValue(\\\"...\\\", forProperty: \\\"...\\\")\\n        // Submit change to the cloud\\n        user?.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}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"User log-out.\"\n}\n[/block]\nThis code sample shows how to inform MOCA that a user has logged out from the app.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"   . . . \\n   // Notify MOCA, the user logged out\\n   MOCAUser * loggedInUser = [[MOCA currentInstance] currentUser];\\n   if (loggedInUser) {\\n        [loggedInUser logout];\\n        // Submit change to the cloud \\n        [loggedInUser saveWithBlock:^(MOCAUser *user, NSError *error) {\\n            if (error) {\\n                NSLog(@\\\"Save user failed: %@\\\", error);\\n            }\\n        }];\\n   }\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \" let loggedInUser: MOCAUser = MOCA.currentInstance().currentUser\\n        if (loggedInUser != nil) {\\n            loggedInUser.logout()\\n            loggedInUser.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\\n                if error != nil {\\n                    print(\\\"Save user failed: (%@)\\\", error ?? \\\"Error not available\\\")\\n                }\\n            })\\n        }\\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Receive push notification.\"\n}\n[/block]\nThis code sample shows how to handle MOCA-specific local push notifications and also track remote push notifications received by the app.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#pragma mark Notifications\\n\\n- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo\\n{\\n    if (MOCA.initialized)\\n    {\\n        [MOCA handleRemoteNotification:userInfo];\\n    }\\n}\\n\\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\\n{\\n    if (MOCA.initialized)\\n    {\\n        [MOCA handleLocalNotification:notification];\\n    }\\n}\\n// Called when your app has been activated by the user selecting an action from a local notification.\\n// A nil action identifier indicates the default action.\\n// You should call the completion handler as soon as you've finished handling the action.\\n- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier\\n    forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler\\n{\\n    if (MOCA.initialized && [MOCA isMocaNotification:notification])\\n    {\\n        [MOCA handleActionWithIdentifier:identifier\\n                    forLocalNotification:notification];\\n    }\\n    if (completionHandler) completionHandler ();\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"#pragma mark Notifications\\nfunc application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {\\n  if MOCA.initialized() {\\n  \\tMOCA.handleRemoteNotification(userInfo)\\n  }\\n}\\n    \\nfunc application(_ application: UIApplication, didReceive notification: UILocalNotification) {\\n  if MOCA.initialized() {\\n  \\tMOCA.handle(notification)\\n  }\\n}\\n    // Called when your app has been activated by the user selecting an action from a local notification.\\n    // A nil action identifier indicates the default action.\\n    // You should call the completion handler as soon as you've finished handling the action.\\nfunc application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {\\n  if MOCA.initialized() && MOCA.isMocaLocalNotification(notification) {\\n  \\tMOCA.handleAction(withIdentifier: identifier, for: notification)\\n  }\\n  if (completionHandler() != nil) {\\n  \\tcompletionHandler()\\n  }\\n}\\n    \\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Register device token\"\n}\n[/block]\nThis code sample shows how to notify MOCA about an existing device token for push notification. This is used when the app is integrated with other third-party push SDKs such as Urban Airship SDK, Parse SDK or a SDK from any other push provider.\n\nIn such a scenario, MOCA is limited to handling its proper local push notifications and remains compatible with existing third-party SDKs.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#pragma mark Notifications\\n\\n-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken\\n{\\n    if ([MOCA initialized]) {\\n        [MOCA registerDeviceToken:deviceToken];\\n    }\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"    // MARK: Notifications\\n    \\nfunc application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\\n  if MOCA.initialized() {\\n  MOCA.registerDeviceToken(deviceToken)\\n  }\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Fetch campaigns\"\n}\n[/block]\nThis code sample shows how to periodically fetch proximity campaigns from MOCA cloud backend. This example uses iOS Background Fetch mechanism to delegate handling of synchronization and content download to iOS.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#pragma mark Fetch Campaigns\\n\\n/// Applications with the \\\"fetch\\\" background mode may be given opportunities to fetch updated\\n// content in the background or when it is convenient for the system. This method will be called\\n// in these situations. You should call the fetchCompletionHandler\\n// as soon as you're finished performing that operation, so the system can accurately\\n// estimate its power and data cost.\\n- (void)application:(UIApplication *)application performFetchWithCompletionHandler:\\n(void (^)(UIBackgroundFetchResult result))completionHandler\\n{\\n    if (MOCA.initialized)\\n    {\\n        [MOCA performFetchWithCompletionHandler:completionHandler];\\n    }\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"    // MARK: Fetch Campaigns\\n    /// Applications with the \\\"fetch\\\" background mode may be given opportunities to fetch updated\\n    // content in the background or when it is convenient for the system. This method will be called\\n    // in these situations. You should call the fetchCompletionHandler\\n    // as soon as you're finished performing that operation, so the system can accurately\\n    // estimate its power and data cost.\\n    \\n    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\\n        if MOCA.initialized() {\\n            MOCA.performFetch(completionHandler: completionHandler)\\n        }\\n    }\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Track in-app navigation.\"\n}\n[/block]\nThis sample code shows how to track custom events with the app, in particular, how to record a user opening a particular app window.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"#Add to each View Controller to be tracked\\n\\n[MOCAEvent track:@\\\"view\\\" forItem:@\\\"screenName\\\" belongingTo:@\\\"screen\\\"];\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"/// Add to each View Controller to be tracked\\n\\nMOCAEvent.track(\\\"view\\\",forItem:\\\"screenName\\\",belongingTo:\\\"screen\\\")\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Track custom event.\"\n}\n[/block]\nThis 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\\n[MOCAEvent track:@”verb\\\" forItem:@”item\\\" belongingTo:@”category” . . . ];\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"// Track custom events\\n\\nMOCAEvent.track(\\\"verb\\\",forItem:\\\"item\\\",belongingTo:\\\"category\\\", ...)\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]","excerpt":"","link_external":false,"version":"59198f1eeba9ac31000185de","user":"55a575ebaaf9cf1900114d73","__v":0,"createdAt":"2015-07-15T07:58:38.276Z","order":4,"type":"basic","parentDoc":null,"category":"59198f20eba9ac31000185e0","githubsync":"","hidden":false,"isReference":false,"childrenPages":[]}

Integration Examples


The typical integration scenarios include handling of the following in-app events: * Launch app * User Login * User Logout * Receive Push Notification * Registered for Remote Push Notifications * Fetch Campaigns * Enter Screen * Custom Events [block:api-header] { "type": "basic", "title": "Launch app" } [/block] This code sample shows how to initialize MOCA SDK on app startup and also handle situations when the app is started by opening a push notification. [block:code] { "codes": [ { "code": "- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n // Init MOCA SDK\n [MOCA initializeSDK];\n if (launchOptions != nil) {\n // Launched from push notification\n NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];\n if (notification) {\n // Notify MOCA the app started from push\n [MOCA handleRemoteNotification:notification];\n }\n }\n // Optionally, set guest properties\n MOCAInstance * currentInstance = [MOCA currentInstance];\n if (currentInstance) {\n [currentInstance setValue:@\"property_1_value\" forProperty:@\"guest_property_1\"];\n [currentInstance setValue:@\"property_2_value\" forProperty:@\"guest_property_2\"];\n [currentInstance setValue:[NSNumber numberWithDouble:property3_value] forProperty:@\"guest_property_3\"];\n \n // Submit change to the cloud \n [currentInstance saveWithBlock:^(MOCAInstance *instance, NSError *error) {\n if (error) {\n NSLog(@\"Save instance failed: %@\", error);\n }\n }];\n }\n}\n", "language": "objectivec" }, { "code": "func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {\n // Init MOCA SDK\n MOCA.initializeSDK()\n if launchOptions != nil {\n // Launched from push notification\n let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] ?? [AnyHashable: Any]()\n if !notification.isEmpty {\n // Notify MOCA the app started from push\n MOCA.handleRemoteNotification(notification)\n }\n }\n let currentInstance: MOCAInstance? = MOCA.currentInstance()\n if currentInstance != nil {\n currentInstance?.setValue(\"property_1_value\", forProperty: \"guest_property_1\")\n currentInstance?.setValue(\"property_2_value\", forProperty: \"guest_property_1\")\n currentInstance?.setValue(2.9, forProperty: \"guest_property_3\")\n currentInstance?.save({ (instance: MOCAInstance?, error: Error?) in\n if (error != nil) {\n print(\"Save instance failed: (%@)\", error ?? \"Error not available\")\n }\n })\n }\n return true\n\n }\n \n", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "User log-in" } [/block] This code sample shows how to inform MOCA that a user has logged into the app. This call should be executed each time the user performs the log in, even if the app persists user session on app close. [block:code] { "codes": [ { "code": " // Notify MOCA, the user logged in. Must be called after each app launch.\n\n NSString * userId = ...\n MOCAUser *user = [[MOCA currentInstance] login:loginMgr.username];\n \n [user setValue:@”paidComplete\" forProperty:@\"paymentStatus\"];\n [user setValue:@\"...\" forProperty:@\"pictureStatus\"];\n [user setValue:@\"...\" forProperty:@\"merchantId\"];\n [user setValue:@\"...\" forProperty:@\"jobTitle\"];\n [user setValue:@\"...\" forProperty:@\"companyName\"];\n [user setValue:@\"...\" forProperty:@\"country\"];\n [user setValue:@\"...\" forProperty:@\"...\"];\n \n NSArray * arrValue = [NSArray arrayWithObjects: @\"Attr1\",@\"Attr2\",@\"Attr3\", nil];\n [user setValue:@\"...\" forProperty:@\"...\"];\n \n // Submit change to the cloud \n [user saveWithBlock:^(MOCAUser *user, NSError *error) {\n if (error) {\n NSLog(@\"Save user failed: %@\", error);\n }\n }];\n}\n", "language": "objectivec" }, { "code": " let userId: String = \"\"\n let user: MOCAUser? = MOCA.currentInstance().login(\"username\")\n user?.setValue(\"paidComplete\",forProperty: \"paymentStatus\")\n user?.setValue(\"...\",forProperty: \"pictureStatus\")\n user?.setValue(\"...\",forProperty: \"merchantId\")\n user?.setValue(\"...\",forProperty: \"jobTitle\")\n user?.setValue(\"...\",forProperty: \"companyName\")\n user?.setValue(\"...\",forProperty: \"country\")\n user?.setValue(\"...\",forProperty: \"...\")\n let arrValue: [Any] = [\"Attr1\", \"Attr2\", \"Attr3\"]\n user?.setValue(\"...\", forProperty: \"...\")\n // Submit change to the cloud\n user?.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\n if error != nil {\n print(\"Save user failed: (%@)\", error ?? \"Error not available\")\n }\n })", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "User log-out." } [/block] This code sample shows how to inform MOCA that a user has logged out from the app. [block:code] { "codes": [ { "code": " . . . \n // Notify MOCA, the user logged out\n MOCAUser * loggedInUser = [[MOCA currentInstance] currentUser];\n if (loggedInUser) {\n [loggedInUser logout];\n // Submit change to the cloud \n [loggedInUser saveWithBlock:^(MOCAUser *user, NSError *error) {\n if (error) {\n NSLog(@\"Save user failed: %@\", error);\n }\n }];\n }\n", "language": "objectivec" }, { "code": " let loggedInUser: MOCAUser = MOCA.currentInstance().currentUser\n if (loggedInUser != nil) {\n loggedInUser.logout()\n loggedInUser.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\n if error != nil {\n print(\"Save user failed: (%@)\", error ?? \"Error not available\")\n }\n })\n }\n", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Receive push notification." } [/block] This code sample shows how to handle MOCA-specific local push notifications and also track remote push notifications received by the app. [block:code] { "codes": [ { "code": "#pragma mark Notifications\n\n- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo\n{\n if (MOCA.initialized)\n {\n [MOCA handleRemoteNotification:userInfo];\n }\n}\n\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\n{\n if (MOCA.initialized)\n {\n [MOCA handleLocalNotification:notification];\n }\n}\n// Called when your app has been activated by the user selecting an action from a local notification.\n// A nil action identifier indicates the default action.\n// You should call the completion handler as soon as you've finished handling the action.\n- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier\n forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler\n{\n if (MOCA.initialized && [MOCA isMocaNotification:notification])\n {\n [MOCA handleActionWithIdentifier:identifier\n forLocalNotification:notification];\n }\n if (completionHandler) completionHandler ();\n}\n", "language": "objectivec" }, { "code": "#pragma mark Notifications\nfunc application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {\n if MOCA.initialized() {\n \tMOCA.handleRemoteNotification(userInfo)\n }\n}\n \nfunc application(_ application: UIApplication, didReceive notification: UILocalNotification) {\n if MOCA.initialized() {\n \tMOCA.handle(notification)\n }\n}\n // Called when your app has been activated by the user selecting an action from a local notification.\n // A nil action identifier indicates the default action.\n // You should call the completion handler as soon as you've finished handling the action.\nfunc application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {\n if MOCA.initialized() && MOCA.isMocaLocalNotification(notification) {\n \tMOCA.handleAction(withIdentifier: identifier, for: notification)\n }\n if (completionHandler() != nil) {\n \tcompletionHandler()\n }\n}\n \n", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Register device token" } [/block] This code sample shows how to notify MOCA about an existing device token for push notification. This is used when the app is integrated with other third-party push SDKs such as Urban Airship SDK, Parse SDK or a SDK from any other push provider. In such a scenario, MOCA is limited to handling its proper local push notifications and remains compatible with existing third-party SDKs. [block:code] { "codes": [ { "code": "#pragma mark Notifications\n\n-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken\n{\n if ([MOCA initialized]) {\n [MOCA registerDeviceToken:deviceToken];\n }\n}\n", "language": "objectivec" }, { "code": " // MARK: Notifications\n \nfunc application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n if MOCA.initialized() {\n MOCA.registerDeviceToken(deviceToken)\n }\n}", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Fetch campaigns" } [/block] This code sample shows how to periodically fetch proximity campaigns from MOCA cloud backend. This example uses iOS Background Fetch mechanism to delegate handling of synchronization and content download to iOS. [block:code] { "codes": [ { "code": "#pragma mark Fetch Campaigns\n\n/// Applications with the \"fetch\" background mode may be given opportunities to fetch updated\n// content in the background or when it is convenient for the system. This method will be called\n// in these situations. You should call the fetchCompletionHandler\n// as soon as you're finished performing that operation, so the system can accurately\n// estimate its power and data cost.\n- (void)application:(UIApplication *)application performFetchWithCompletionHandler:\n(void (^)(UIBackgroundFetchResult result))completionHandler\n{\n if (MOCA.initialized)\n {\n [MOCA performFetchWithCompletionHandler:completionHandler];\n }\n}\n", "language": "objectivec" }, { "code": " // MARK: Fetch Campaigns\n /// Applications with the \"fetch\" background mode may be given opportunities to fetch updated\n // content in the background or when it is convenient for the system. This method will be called\n // in these situations. You should call the fetchCompletionHandler\n // as soon as you're finished performing that operation, so the system can accurately\n // estimate its power and data cost.\n \n func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.performFetch(completionHandler: completionHandler)\n }\n }", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Track in-app navigation." } [/block] This sample code shows how to track custom events with the app, in particular, how to record a user opening a particular app window. [block:code] { "codes": [ { "code": "#Add to each View Controller to be tracked\n\n[MOCAEvent track:@\"view\" forItem:@\"screenName\" belongingTo:@\"screen\"];\n", "language": "objectivec" }, { "code": "/// Add to each View Controller to be tracked\n\nMOCAEvent.track(\"view\",forItem:\"screenName\",belongingTo:\"screen\")", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Track custom event." } [/block] This sample code shows how to track a generic, custom event within the app. [block:code] { "codes": [ { "code": "# Track custom events\n\n[MOCAEvent track:@”verb\" forItem:@”item\" belongingTo:@”category” . . . ];\n", "language": "objectivec" }, { "code": "// Track custom events\n\nMOCAEvent.track(\"verb\",forItem:\"item\",belongingTo:\"category\", ...)", "language": "swift" } ] } [/block]
The typical integration scenarios include handling of the following in-app events: * Launch app * User Login * User Logout * Receive Push Notification * Registered for Remote Push Notifications * Fetch Campaigns * Enter Screen * Custom Events [block:api-header] { "type": "basic", "title": "Launch app" } [/block] This code sample shows how to initialize MOCA SDK on app startup and also handle situations when the app is started by opening a push notification. [block:code] { "codes": [ { "code": "- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n // Init MOCA SDK\n [MOCA initializeSDK];\n if (launchOptions != nil) {\n // Launched from push notification\n NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];\n if (notification) {\n // Notify MOCA the app started from push\n [MOCA handleRemoteNotification:notification];\n }\n }\n // Optionally, set guest properties\n MOCAInstance * currentInstance = [MOCA currentInstance];\n if (currentInstance) {\n [currentInstance setValue:@\"property_1_value\" forProperty:@\"guest_property_1\"];\n [currentInstance setValue:@\"property_2_value\" forProperty:@\"guest_property_2\"];\n [currentInstance setValue:[NSNumber numberWithDouble:property3_value] forProperty:@\"guest_property_3\"];\n \n // Submit change to the cloud \n [currentInstance saveWithBlock:^(MOCAInstance *instance, NSError *error) {\n if (error) {\n NSLog(@\"Save instance failed: %@\", error);\n }\n }];\n }\n}\n", "language": "objectivec" }, { "code": "func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {\n // Init MOCA SDK\n MOCA.initializeSDK()\n if launchOptions != nil {\n // Launched from push notification\n let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] ?? [AnyHashable: Any]()\n if !notification.isEmpty {\n // Notify MOCA the app started from push\n MOCA.handleRemoteNotification(notification)\n }\n }\n let currentInstance: MOCAInstance? = MOCA.currentInstance()\n if currentInstance != nil {\n currentInstance?.setValue(\"property_1_value\", forProperty: \"guest_property_1\")\n currentInstance?.setValue(\"property_2_value\", forProperty: \"guest_property_1\")\n currentInstance?.setValue(2.9, forProperty: \"guest_property_3\")\n currentInstance?.save({ (instance: MOCAInstance?, error: Error?) in\n if (error != nil) {\n print(\"Save instance failed: (%@)\", error ?? \"Error not available\")\n }\n })\n }\n return true\n\n }\n \n", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "User log-in" } [/block] This code sample shows how to inform MOCA that a user has logged into the app. This call should be executed each time the user performs the log in, even if the app persists user session on app close. [block:code] { "codes": [ { "code": " // Notify MOCA, the user logged in. Must be called after each app launch.\n\n NSString * userId = ...\n MOCAUser *user = [[MOCA currentInstance] login:loginMgr.username];\n \n [user setValue:@”paidComplete\" forProperty:@\"paymentStatus\"];\n [user setValue:@\"...\" forProperty:@\"pictureStatus\"];\n [user setValue:@\"...\" forProperty:@\"merchantId\"];\n [user setValue:@\"...\" forProperty:@\"jobTitle\"];\n [user setValue:@\"...\" forProperty:@\"companyName\"];\n [user setValue:@\"...\" forProperty:@\"country\"];\n [user setValue:@\"...\" forProperty:@\"...\"];\n \n NSArray * arrValue = [NSArray arrayWithObjects: @\"Attr1\",@\"Attr2\",@\"Attr3\", nil];\n [user setValue:@\"...\" forProperty:@\"...\"];\n \n // Submit change to the cloud \n [user saveWithBlock:^(MOCAUser *user, NSError *error) {\n if (error) {\n NSLog(@\"Save user failed: %@\", error);\n }\n }];\n}\n", "language": "objectivec" }, { "code": " let userId: String = \"\"\n let user: MOCAUser? = MOCA.currentInstance().login(\"username\")\n user?.setValue(\"paidComplete\",forProperty: \"paymentStatus\")\n user?.setValue(\"...\",forProperty: \"pictureStatus\")\n user?.setValue(\"...\",forProperty: \"merchantId\")\n user?.setValue(\"...\",forProperty: \"jobTitle\")\n user?.setValue(\"...\",forProperty: \"companyName\")\n user?.setValue(\"...\",forProperty: \"country\")\n user?.setValue(\"...\",forProperty: \"...\")\n let arrValue: [Any] = [\"Attr1\", \"Attr2\", \"Attr3\"]\n user?.setValue(\"...\", forProperty: \"...\")\n // Submit change to the cloud\n user?.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\n if error != nil {\n print(\"Save user failed: (%@)\", error ?? \"Error not available\")\n }\n })", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "User log-out." } [/block] This code sample shows how to inform MOCA that a user has logged out from the app. [block:code] { "codes": [ { "code": " . . . \n // Notify MOCA, the user logged out\n MOCAUser * loggedInUser = [[MOCA currentInstance] currentUser];\n if (loggedInUser) {\n [loggedInUser logout];\n // Submit change to the cloud \n [loggedInUser saveWithBlock:^(MOCAUser *user, NSError *error) {\n if (error) {\n NSLog(@\"Save user failed: %@\", error);\n }\n }];\n }\n", "language": "objectivec" }, { "code": " let loggedInUser: MOCAUser = MOCA.currentInstance().currentUser\n if (loggedInUser != nil) {\n loggedInUser.logout()\n loggedInUser.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\n if error != nil {\n print(\"Save user failed: (%@)\", error ?? \"Error not available\")\n }\n })\n }\n", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Receive push notification." } [/block] This code sample shows how to handle MOCA-specific local push notifications and also track remote push notifications received by the app. [block:code] { "codes": [ { "code": "#pragma mark Notifications\n\n- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo\n{\n if (MOCA.initialized)\n {\n [MOCA handleRemoteNotification:userInfo];\n }\n}\n\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\n{\n if (MOCA.initialized)\n {\n [MOCA handleLocalNotification:notification];\n }\n}\n// Called when your app has been activated by the user selecting an action from a local notification.\n// A nil action identifier indicates the default action.\n// You should call the completion handler as soon as you've finished handling the action.\n- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier\n forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler\n{\n if (MOCA.initialized && [MOCA isMocaNotification:notification])\n {\n [MOCA handleActionWithIdentifier:identifier\n forLocalNotification:notification];\n }\n if (completionHandler) completionHandler ();\n}\n", "language": "objectivec" }, { "code": "#pragma mark Notifications\nfunc application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {\n if MOCA.initialized() {\n \tMOCA.handleRemoteNotification(userInfo)\n }\n}\n \nfunc application(_ application: UIApplication, didReceive notification: UILocalNotification) {\n if MOCA.initialized() {\n \tMOCA.handle(notification)\n }\n}\n // Called when your app has been activated by the user selecting an action from a local notification.\n // A nil action identifier indicates the default action.\n // You should call the completion handler as soon as you've finished handling the action.\nfunc application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {\n if MOCA.initialized() && MOCA.isMocaLocalNotification(notification) {\n \tMOCA.handleAction(withIdentifier: identifier, for: notification)\n }\n if (completionHandler() != nil) {\n \tcompletionHandler()\n }\n}\n \n", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Register device token" } [/block] This code sample shows how to notify MOCA about an existing device token for push notification. This is used when the app is integrated with other third-party push SDKs such as Urban Airship SDK, Parse SDK or a SDK from any other push provider. In such a scenario, MOCA is limited to handling its proper local push notifications and remains compatible with existing third-party SDKs. [block:code] { "codes": [ { "code": "#pragma mark Notifications\n\n-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken\n{\n if ([MOCA initialized]) {\n [MOCA registerDeviceToken:deviceToken];\n }\n}\n", "language": "objectivec" }, { "code": " // MARK: Notifications\n \nfunc application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n if MOCA.initialized() {\n MOCA.registerDeviceToken(deviceToken)\n }\n}", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Fetch campaigns" } [/block] This code sample shows how to periodically fetch proximity campaigns from MOCA cloud backend. This example uses iOS Background Fetch mechanism to delegate handling of synchronization and content download to iOS. [block:code] { "codes": [ { "code": "#pragma mark Fetch Campaigns\n\n/// Applications with the \"fetch\" background mode may be given opportunities to fetch updated\n// content in the background or when it is convenient for the system. This method will be called\n// in these situations. You should call the fetchCompletionHandler\n// as soon as you're finished performing that operation, so the system can accurately\n// estimate its power and data cost.\n- (void)application:(UIApplication *)application performFetchWithCompletionHandler:\n(void (^)(UIBackgroundFetchResult result))completionHandler\n{\n if (MOCA.initialized)\n {\n [MOCA performFetchWithCompletionHandler:completionHandler];\n }\n}\n", "language": "objectivec" }, { "code": " // MARK: Fetch Campaigns\n /// Applications with the \"fetch\" background mode may be given opportunities to fetch updated\n // content in the background or when it is convenient for the system. This method will be called\n // in these situations. You should call the fetchCompletionHandler\n // as soon as you're finished performing that operation, so the system can accurately\n // estimate its power and data cost.\n \n func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.performFetch(completionHandler: completionHandler)\n }\n }", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Track in-app navigation." } [/block] This sample code shows how to track custom events with the app, in particular, how to record a user opening a particular app window. [block:code] { "codes": [ { "code": "#Add to each View Controller to be tracked\n\n[MOCAEvent track:@\"view\" forItem:@\"screenName\" belongingTo:@\"screen\"];\n", "language": "objectivec" }, { "code": "/// Add to each View Controller to be tracked\n\nMOCAEvent.track(\"view\",forItem:\"screenName\",belongingTo:\"screen\")", "language": "swift" } ] } [/block] [block:api-header] { "type": "basic", "title": "Track custom event." } [/block] This sample code shows how to track a generic, custom event within the app. [block:code] { "codes": [ { "code": "# Track custom events\n\n[MOCAEvent track:@”verb\" forItem:@”item\" belongingTo:@”category” . . . ];\n", "language": "objectivec" }, { "code": "// Track custom events\n\nMOCAEvent.track(\"verb\",forItem:\"item\",belongingTo:\"category\", ...)", "language": "swift" } ] } [/block]
{"_id":"59198f20eba9ac31000185f7","hidden":false,"parentDoc":null,"category":"59198f20eba9ac31000185e0","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":5,"type":"basic","version":"59198f1eeba9ac31000185de","__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,"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":"59198f20eba9ac31000185f8","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":"59198f1eeba9ac31000185de","api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"category":"59198f20eba9ac31000185e0","excerpt":"","isReference":false,"link_url":"","sync_unique":"","__v":0,"order":6,"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":"59198f21eba9ac3100018601","category":"59198f20eba9ac31000185e1","hidden":false,"link_external":false,"link_url":"","order":0,"slug":"moca-ios-sdk-api","sync_unique":"","body":"The **MOCA shared object** is a main entry point to MOCA APIs.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@interface MOCA : NSObject\\n\\n// Gets the version of the MOCA library.\\n+ (NSString*) version;\\n\\n// Initializes the library with the configuration from MOCAConfig.plist resource file\\n+ (BOOL) initializeSDK:(MOCAConfig *)config;\\n\\n// Gets library configuration.\\n+ (MOCAConfig*) config;\\n\\n// Gets the application key once successfully initialized.\\n+ (NSString*) appKey;\\n\\n// Gets the application secret once successfully initialized.\\n+ (NSString*) appSecret;\\n\\n// Returns `YES` if the MOCA library has been initialized and is ready for use.\\n+ (BOOL) initialized;\\n\\n// Gets the current MOCA app instance object.\\n+ (MOCAInstance*) currentInstance;\\n\\n// Gets the current proximity service object. Available starting from iOS 7.\\n+ (MOCAProximityService*) proximityService;\\n\\n// Gets access to MOCA inbox.\\u000b+ (MOCAInbox*) inbox;\\n\\n// Gets the current log level of MOCA library.\\n+ (MOCALogLevel) logLevel;\\n\\n// Sets the log level.\\n+ (void) setLogLevel:(MOCALogLevel)logLevel;\\n\\n// Tells MOCA that it can begin a cloud fetch operation if it has data to download.\\n+(BOOL)performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;\\n\\n// Updates the push device token and registers the token with MOCA cloud.\\n+(void)registerDeviceToken:(NSData*)deviceToken;\\n\\n// Tells MOCA that a remote push notification has been received by the application.\\n+(void)handleRemoteNotification:(NSDictionary *)userInfo;\\n\\n// Tells MOCA that a local push notification has been received by the application.\\n+(void)handleLocalNotification:(UILocalNotification*)notification;\\n\\n// Checks if this specific local notifaction contains MOCA content.\\n+(BOOL)isMOCANotification:(UILocalNotification*)notification;\\n\\u000b// Called when your app has been activated by the user selecting an action \\u000b// from a local notification.\\n+(BOOL)handleActionWithIdentifier:(NSString*)identifier \\u000b             forLocalNotification:(UILocalNotification*)notification;\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"\\n    // Gets the version of the MOCA library.\\n    func version() -> Int\\n    \\n    // Initializes the library with the configuration from MOCAConfig.plist resource file\\n    func initializeSDK(_ config: MOCAConfig) -> Bool\\n    // Gets library configuration.\\n    func config() -> MOCAConfig\\n    // Gets the application key once successfully initialized.\\n    func appKey() -> String\\n    // Gets the application secret once successfully initialized.\\n    \\n    func appSecret() -> String\\n    \\n    // Returns `YES` if the MOCA library has been initialized and is ready for use.\\n    \\n    func initialized() -> Bool\\n    \\n    // Gets the current MOCA app instance object.\\n    \\n    func currentInstance() -> MOCAInstance\\n    \\n    // Gets the current proximity service object. Available starting from iOS 7.\\n    \\n    func proximityService() -> MOCAProximityService\\n    \\n    // Gets access to MOCA inbox.+ (MOCAInbox*) inbox;\\n    // Gets the current log level of MOCA library.\\n    func logLevel() -> MOCALogLevel\\n    \\n    // Sets the log level.\\n    func setLogLevel(_ logLevel: MOCALogLevel)\\n    \\n    // Tells MOCA that it can begin a cloud fetch operation if it has data to download.\\n    func performFetch(withCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) -> Bool\\n    \\n    // Updates the push device token and registers the token with MOCA cloud.\\n    func registerDeviceToken(_ deviceToken: Data)\\n    \\n    // Tells MOCA that a remote push notification has been received by the application.\\n    func handleRemoteNotification(_ userInfo: [AnyHashable: Any])\\n    \\n    // Tells MOCA that a local push notification has been received by the application.\\n    func handle(_ notification: UILocalNotification)\\n    \\n    // Checks if this specific local notifaction contains MOCA content.\\n    func isMOCANotification(_ notification: UILocalNotification) -> Bool\\n    \\n    \\n    // Called when your app has been activated by the user selecting an action // from a local notification.\\n    func handleAction(withIdentifier identifier: String?, for localNotification: UILocalNotification)\\n\\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\nStart / stop certain MOCA SDK services\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n * Get status of the proximity service.\\n *\\n * @return YES if the proximity service is available and enabled, NO otherwise.\\n */\\n+ (BOOL)proximityEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\\n\\n/**\\n * Enables/disables the proximity service.\\n * @param enable - if YES, start proximity service, otherwise stop proximity service.\\n */\\n+ (void)setProximityEnabled:(BOOL)enable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\\n\\n/**\\n * Starts/stops MOCA remote push notification service (APNS).\\n * @param enabled - YES to register the token/start the service, NO to unregister the token/stop service.\\n */\\n+(void)setRemotePushEnabled:(BOOL)enabled;\\n\\n/**\\n * Return YES if MOCA remote push notifications are available and enabled.\\n * @return YES if the the service is enabled, NO otherwise.\\n */\\n+(BOOL)remotePushEnabled;\\n\\n/**\\n * Return YES if MOCA geolocation tracking service is available and enabled.\\n * @return YES if the the service is enabled, NO otherwise.\\n */\\n+(BOOL)geoTrackingEnabled;\\n\\n/**\\n * Starts/stops MOCA geolocation tracking service.\\n * This requires event tracking service to be enabled as well in order to\\n * submit data to the cloud.\\n * @param enabled - YES to start the service, NO to stop service.\\n */\\n+(void)setGeoTrackingEnabled:(BOOL)enabled;\\n\\n/**\\n * Return YES if MOCA event tracking service is available and enabled.\\n * @return YES if the the service is enabled, NO otherwise.\\n */\\n+(BOOL)eventTrackingEnabled;\\n\\n/**\\n * Starts/stops MOCA event tracking service.\\n * @param enabled - YES to start the service, NO to stop service.\\n *\\n * If this service is enabled, MOCA collects and submits tracked events\\n * to MOCA cloud.\\n */\\n+(void)setEventTrackingEnabled:(BOOL)enabled;\\n\\n/**\\n * Get status of the recommendation service.\\n *\\n * @return YES if the service is available and enabled, NO otherwise.\\n */\\n+ (BOOL)recoEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\\n\\n/**\\n * Enables/disables the recommendations service.\\n * @param enable - if YES, start the service, otherwise stop it.\\n */\\n+ (void)setRecoEnabled:(BOOL)enable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\\n\\n/**\\n * Get status of the WiFi only transfer constraint.\\n *\\n * @return YES if the SDK is allowed to transmit data only when Wifi is available.\\n *         NO otherwise.\\n */\\n+ (BOOL)wifiOnlyEnabled;\\n\\n/**\\n * Enables/disables the \\\"WiFi only\\\" transfer contraint.\\n * @param enabled - if YES the SDK is allowed to transmit data only when Wifi is available.\\n *         NO otherwise.\\n */\\n+ (void)setWifiOnlyEnabled:(BOOL)enabled;\\n\\n/**\\n * Get status of the Indoor Analytics service. \\n */\\n+ (BOOL)indoorAnalyticsEnabled;\\n\\n/**\\n * Enables / Disables Indoor Analytics tracking. Available for venues with Indoor Location technologies\\n * installed. SDK will remember this setting in subsequent initializations.\\n * @param enabled - YES to enable, NO to disable\\n */\\n+ (void)setIndoorAnalyticsEnabled:(BOOL)enabled;\\n\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]","version":"59198f1eeba9ac31000185de","excerpt":"","isReference":false,"parentDoc":null,"createdAt":"2015-07-15T07:55:24.877Z","next":{"description":"","pages":[]},"project":"559a61d2dbcfd20d00710b39","title":"MOCA API","user":"55a575ebaaf9cf1900114d73","__v":0,"api":{"auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":""},"githubsync":"","type":"basic","updates":[],"childrenPages":[]}

MOCA API


The **MOCA shared object** is a main entry point to MOCA APIs. [block:code] { "codes": [ { "code": "@interface MOCA : NSObject\n\n// Gets the version of the MOCA library.\n+ (NSString*) version;\n\n// Initializes the library with the configuration from MOCAConfig.plist resource file\n+ (BOOL) initializeSDK:(MOCAConfig *)config;\n\n// Gets library configuration.\n+ (MOCAConfig*) config;\n\n// Gets the application key once successfully initialized.\n+ (NSString*) appKey;\n\n// Gets the application secret once successfully initialized.\n+ (NSString*) appSecret;\n\n// Returns `YES` if the MOCA library has been initialized and is ready for use.\n+ (BOOL) initialized;\n\n// Gets the current MOCA app instance object.\n+ (MOCAInstance*) currentInstance;\n\n// Gets the current proximity service object. Available starting from iOS 7.\n+ (MOCAProximityService*) proximityService;\n\n// Gets access to MOCA inbox.\u000b+ (MOCAInbox*) inbox;\n\n// Gets the current log level of MOCA library.\n+ (MOCALogLevel) logLevel;\n\n// Sets the log level.\n+ (void) setLogLevel:(MOCALogLevel)logLevel;\n\n// Tells MOCA that it can begin a cloud fetch operation if it has data to download.\n+(BOOL)performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;\n\n// Updates the push device token and registers the token with MOCA cloud.\n+(void)registerDeviceToken:(NSData*)deviceToken;\n\n// Tells MOCA that a remote push notification has been received by the application.\n+(void)handleRemoteNotification:(NSDictionary *)userInfo;\n\n// Tells MOCA that a local push notification has been received by the application.\n+(void)handleLocalNotification:(UILocalNotification*)notification;\n\n// Checks if this specific local notifaction contains MOCA content.\n+(BOOL)isMOCANotification:(UILocalNotification*)notification;\n\u000b// Called when your app has been activated by the user selecting an action \u000b// from a local notification.\n+(BOOL)handleActionWithIdentifier:(NSString*)identifier \u000b forLocalNotification:(UILocalNotification*)notification;\n", "language": "objectivec" }, { "code": "\n // Gets the version of the MOCA library.\n func version() -> Int\n \n // Initializes the library with the configuration from MOCAConfig.plist resource file\n func initializeSDK(_ config: MOCAConfig) -> Bool\n // Gets library configuration.\n func config() -> MOCAConfig\n // Gets the application key once successfully initialized.\n func appKey() -> String\n // Gets the application secret once successfully initialized.\n \n func appSecret() -> String\n \n // Returns `YES` if the MOCA library has been initialized and is ready for use.\n \n func initialized() -> Bool\n \n // Gets the current MOCA app instance object.\n \n func currentInstance() -> MOCAInstance\n \n // Gets the current proximity service object. Available starting from iOS 7.\n \n func proximityService() -> MOCAProximityService\n \n // Gets access to MOCA inbox.+ (MOCAInbox*) inbox;\n // Gets the current log level of MOCA library.\n func logLevel() -> MOCALogLevel\n \n // Sets the log level.\n func setLogLevel(_ logLevel: MOCALogLevel)\n \n // Tells MOCA that it can begin a cloud fetch operation if it has data to download.\n func performFetch(withCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) -> Bool\n \n // Updates the push device token and registers the token with MOCA cloud.\n func registerDeviceToken(_ deviceToken: Data)\n \n // Tells MOCA that a remote push notification has been received by the application.\n func handleRemoteNotification(_ userInfo: [AnyHashable: Any])\n \n // Tells MOCA that a local push notification has been received by the application.\n func handle(_ notification: UILocalNotification)\n \n // Checks if this specific local notifaction contains MOCA content.\n func isMOCANotification(_ notification: UILocalNotification) -> Bool\n \n \n // Called when your app has been activated by the user selecting an action // from a local notification.\n func handleAction(withIdentifier identifier: String?, for localNotification: UILocalNotification)\n\n", "language": "swift" } ] } [/block] Start / stop certain MOCA SDK services [block:code] { "codes": [ { "code": "/**\n * Get status of the proximity service.\n *\n * @return YES if the proximity service is available and enabled, NO otherwise.\n */\n+ (BOOL)proximityEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Enables/disables the proximity service.\n * @param enable - if YES, start proximity service, otherwise stop proximity service.\n */\n+ (void)setProximityEnabled:(BOOL)enable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Starts/stops MOCA remote push notification service (APNS).\n * @param enabled - YES to register the token/start the service, NO to unregister the token/stop service.\n */\n+(void)setRemotePushEnabled:(BOOL)enabled;\n\n/**\n * Return YES if MOCA remote push notifications are available and enabled.\n * @return YES if the the service is enabled, NO otherwise.\n */\n+(BOOL)remotePushEnabled;\n\n/**\n * Return YES if MOCA geolocation tracking service is available and enabled.\n * @return YES if the the service is enabled, NO otherwise.\n */\n+(BOOL)geoTrackingEnabled;\n\n/**\n * Starts/stops MOCA geolocation tracking service.\n * This requires event tracking service to be enabled as well in order to\n * submit data to the cloud.\n * @param enabled - YES to start the service, NO to stop service.\n */\n+(void)setGeoTrackingEnabled:(BOOL)enabled;\n\n/**\n * Return YES if MOCA event tracking service is available and enabled.\n * @return YES if the the service is enabled, NO otherwise.\n */\n+(BOOL)eventTrackingEnabled;\n\n/**\n * Starts/stops MOCA event tracking service.\n * @param enabled - YES to start the service, NO to stop service.\n *\n * If this service is enabled, MOCA collects and submits tracked events\n * to MOCA cloud.\n */\n+(void)setEventTrackingEnabled:(BOOL)enabled;\n\n/**\n * Get status of the recommendation service.\n *\n * @return YES if the service is available and enabled, NO otherwise.\n */\n+ (BOOL)recoEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Enables/disables the recommendations service.\n * @param enable - if YES, start the service, otherwise stop it.\n */\n+ (void)setRecoEnabled:(BOOL)enable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Get status of the WiFi only transfer constraint.\n *\n * @return YES if the SDK is allowed to transmit data only when Wifi is available.\n * NO otherwise.\n */\n+ (BOOL)wifiOnlyEnabled;\n\n/**\n * Enables/disables the \"WiFi only\" transfer contraint.\n * @param enabled - if YES the SDK is allowed to transmit data only when Wifi is available.\n * NO otherwise.\n */\n+ (void)setWifiOnlyEnabled:(BOOL)enabled;\n\n/**\n * Get status of the Indoor Analytics service. \n */\n+ (BOOL)indoorAnalyticsEnabled;\n\n/**\n * Enables / Disables Indoor Analytics tracking. Available for venues with Indoor Location technologies\n * installed. SDK will remember this setting in subsequent initializations.\n * @param enabled - YES to enable, NO to disable\n */\n+ (void)setIndoorAnalyticsEnabled:(BOOL)enabled;\n\n", "language": "objectivec" } ] } [/block]
The **MOCA shared object** is a main entry point to MOCA APIs. [block:code] { "codes": [ { "code": "@interface MOCA : NSObject\n\n// Gets the version of the MOCA library.\n+ (NSString*) version;\n\n// Initializes the library with the configuration from MOCAConfig.plist resource file\n+ (BOOL) initializeSDK:(MOCAConfig *)config;\n\n// Gets library configuration.\n+ (MOCAConfig*) config;\n\n// Gets the application key once successfully initialized.\n+ (NSString*) appKey;\n\n// Gets the application secret once successfully initialized.\n+ (NSString*) appSecret;\n\n// Returns `YES` if the MOCA library has been initialized and is ready for use.\n+ (BOOL) initialized;\n\n// Gets the current MOCA app instance object.\n+ (MOCAInstance*) currentInstance;\n\n// Gets the current proximity service object. Available starting from iOS 7.\n+ (MOCAProximityService*) proximityService;\n\n// Gets access to MOCA inbox.\u000b+ (MOCAInbox*) inbox;\n\n// Gets the current log level of MOCA library.\n+ (MOCALogLevel) logLevel;\n\n// Sets the log level.\n+ (void) setLogLevel:(MOCALogLevel)logLevel;\n\n// Tells MOCA that it can begin a cloud fetch operation if it has data to download.\n+(BOOL)performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;\n\n// Updates the push device token and registers the token with MOCA cloud.\n+(void)registerDeviceToken:(NSData*)deviceToken;\n\n// Tells MOCA that a remote push notification has been received by the application.\n+(void)handleRemoteNotification:(NSDictionary *)userInfo;\n\n// Tells MOCA that a local push notification has been received by the application.\n+(void)handleLocalNotification:(UILocalNotification*)notification;\n\n// Checks if this specific local notifaction contains MOCA content.\n+(BOOL)isMOCANotification:(UILocalNotification*)notification;\n\u000b// Called when your app has been activated by the user selecting an action \u000b// from a local notification.\n+(BOOL)handleActionWithIdentifier:(NSString*)identifier \u000b forLocalNotification:(UILocalNotification*)notification;\n", "language": "objectivec" }, { "code": "\n // Gets the version of the MOCA library.\n func version() -> Int\n \n // Initializes the library with the configuration from MOCAConfig.plist resource file\n func initializeSDK(_ config: MOCAConfig) -> Bool\n // Gets library configuration.\n func config() -> MOCAConfig\n // Gets the application key once successfully initialized.\n func appKey() -> String\n // Gets the application secret once successfully initialized.\n \n func appSecret() -> String\n \n // Returns `YES` if the MOCA library has been initialized and is ready for use.\n \n func initialized() -> Bool\n \n // Gets the current MOCA app instance object.\n \n func currentInstance() -> MOCAInstance\n \n // Gets the current proximity service object. Available starting from iOS 7.\n \n func proximityService() -> MOCAProximityService\n \n // Gets access to MOCA inbox.+ (MOCAInbox*) inbox;\n // Gets the current log level of MOCA library.\n func logLevel() -> MOCALogLevel\n \n // Sets the log level.\n func setLogLevel(_ logLevel: MOCALogLevel)\n \n // Tells MOCA that it can begin a cloud fetch operation if it has data to download.\n func performFetch(withCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) -> Bool\n \n // Updates the push device token and registers the token with MOCA cloud.\n func registerDeviceToken(_ deviceToken: Data)\n \n // Tells MOCA that a remote push notification has been received by the application.\n func handleRemoteNotification(_ userInfo: [AnyHashable: Any])\n \n // Tells MOCA that a local push notification has been received by the application.\n func handle(_ notification: UILocalNotification)\n \n // Checks if this specific local notifaction contains MOCA content.\n func isMOCANotification(_ notification: UILocalNotification) -> Bool\n \n \n // Called when your app has been activated by the user selecting an action // from a local notification.\n func handleAction(withIdentifier identifier: String?, for localNotification: UILocalNotification)\n\n", "language": "swift" } ] } [/block] Start / stop certain MOCA SDK services [block:code] { "codes": [ { "code": "/**\n * Get status of the proximity service.\n *\n * @return YES if the proximity service is available and enabled, NO otherwise.\n */\n+ (BOOL)proximityEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Enables/disables the proximity service.\n * @param enable - if YES, start proximity service, otherwise stop proximity service.\n */\n+ (void)setProximityEnabled:(BOOL)enable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Starts/stops MOCA remote push notification service (APNS).\n * @param enabled - YES to register the token/start the service, NO to unregister the token/stop service.\n */\n+(void)setRemotePushEnabled:(BOOL)enabled;\n\n/**\n * Return YES if MOCA remote push notifications are available and enabled.\n * @return YES if the the service is enabled, NO otherwise.\n */\n+(BOOL)remotePushEnabled;\n\n/**\n * Return YES if MOCA geolocation tracking service is available and enabled.\n * @return YES if the the service is enabled, NO otherwise.\n */\n+(BOOL)geoTrackingEnabled;\n\n/**\n * Starts/stops MOCA geolocation tracking service.\n * This requires event tracking service to be enabled as well in order to\n * submit data to the cloud.\n * @param enabled - YES to start the service, NO to stop service.\n */\n+(void)setGeoTrackingEnabled:(BOOL)enabled;\n\n/**\n * Return YES if MOCA event tracking service is available and enabled.\n * @return YES if the the service is enabled, NO otherwise.\n */\n+(BOOL)eventTrackingEnabled;\n\n/**\n * Starts/stops MOCA event tracking service.\n * @param enabled - YES to start the service, NO to stop service.\n *\n * If this service is enabled, MOCA collects and submits tracked events\n * to MOCA cloud.\n */\n+(void)setEventTrackingEnabled:(BOOL)enabled;\n\n/**\n * Get status of the recommendation service.\n *\n * @return YES if the service is available and enabled, NO otherwise.\n */\n+ (BOOL)recoEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Enables/disables the recommendations service.\n * @param enable - if YES, start the service, otherwise stop it.\n */\n+ (void)setRecoEnabled:(BOOL)enable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0);\n\n/**\n * Get status of the WiFi only transfer constraint.\n *\n * @return YES if the SDK is allowed to transmit data only when Wifi is available.\n * NO otherwise.\n */\n+ (BOOL)wifiOnlyEnabled;\n\n/**\n * Enables/disables the \"WiFi only\" transfer contraint.\n * @param enabled - if YES the SDK is allowed to transmit data only when Wifi is available.\n * NO otherwise.\n */\n+ (void)setWifiOnlyEnabled:(BOOL)enabled;\n\n/**\n * Get status of the Indoor Analytics service. \n */\n+ (BOOL)indoorAnalyticsEnabled;\n\n/**\n * Enables / Disables Indoor Analytics tracking. Available for venues with Indoor Location technologies\n * installed. SDK will remember this setting in subsequent initializations.\n * @param enabled - YES to enable, NO to disable\n */\n+ (void)setIndoorAnalyticsEnabled:(BOOL)enabled;\n\n", "language": "objectivec" } ] } [/block]
{"_id":"59198f21eba9ac3100018602","api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required"},"category":"59198f20eba9ac31000185e1","parentDoc":null,"sync_unique":"","updates":[],"user":"559a618bdbcfd20d00710b38","isReference":false,"order":1,"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":"59198f1eeba9ac31000185de","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\": \"MOCAInstance * theInstance = [MOCA currentInstance];\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"var theInstance = MOCA.currentInstance()\",\n      \"language\": \"swift\"\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- (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      \"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}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"info\",\n  \"body\": \"MOCA properties are internally stored in a local SQLite database\"\n}\n[/block]\nThe instance object holds predefined properties collected automatically:\n- `Device-oriented`, including:\n - `device_model` – the device model (i.e. iPhone 4S, iPhone 5C, iPhone 5S)\n - `device_type` – the type of device (i.e. iPhone, iPad, Simulator)\n - `local_timezone` – the local time zone's abbreviated name (i.e. EDT, GMT, PST)\n - `country` – the country code as defined by the user in `Settings\\General\\International\\Regional Format (NSLocaleCountryCode)`.\n - `lang` – the user preferred language code as defined in `Settings\\General\\International\\Language (NSLocaleLanguageCode)`.\n - `os_name` – the OS name (i.e. “iOS”)\n - `os_version` – the OS version (i.e. “7.0”)\n - `carrier_name` – the name of the user’s home cellular service provider (CTCarrier carrierName)\n - `carrier_country` – the ISO country code for the user’s cellular service provider.\n- App-oriented, including:\n - `app_name` – the app name\n - `app_version` – the app version number\n - `vendor_id` – the unique identifier for app vendor (i.e. UUID string)\n - `moca_version` – the version of MOCA SDK\n - `apns_token` – the push notification device token (optional)\n - `session` – session counter (how many times a user launched the app).\n\n- The object may also store any custom property-value pairs. \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\": \"#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      \"code\": \"let theInstance = MOCA.currentInstance()\\nif (theInstance != nil) {\\nlet adId: String = ASIdentifierManager.shared().advertisingIdentifier.uuidString\\ntheInstance?.setValue(adId, forProperty: \\\"_ad_id\\\")\\ntheInstance?.setValue(\\\"red\\\", forProperty: \\\"favorite-color\\\")\\ntheInstance?.setValue(\\\"women-cloth\\\", forProperty: \\\"last-search\\\")\\n// Asynchronously save the instance to the cloud.\\ntheInstance?.save({(_ instance: MOCAInstance?, _ error: Error?) -> Void in\\nif error != nil {\\nprint(\\\"Save instance failed: (%@)\\\", error ?? \\\"Error not available\\\")\\n}\\n})\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]","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": "MOCAInstance * theInstance = [MOCA currentInstance];", "language": "objectivec" }, { "code": "var theInstance = MOCA.currentInstance()", "language": "swift" } ] } [/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- (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" }, { "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" } ] } [/block] [block:callout] { "type": "info", "title": "info", "body": "MOCA properties are internally stored in a local SQLite database" } [/block] The instance object holds predefined properties collected automatically: - `Device-oriented`, including: - `device_model` – the device model (i.e. iPhone 4S, iPhone 5C, iPhone 5S) - `device_type` – the type of device (i.e. iPhone, iPad, Simulator) - `local_timezone` – the local time zone's abbreviated name (i.e. EDT, GMT, PST) - `country` – the country code as defined by the user in `Settings\General\International\Regional Format (NSLocaleCountryCode)`. - `lang` – the user preferred language code as defined in `Settings\General\International\Language (NSLocaleLanguageCode)`. - `os_name` – the OS name (i.e. “iOS”) - `os_version` – the OS version (i.e. “7.0”) - `carrier_name` – the name of the user’s home cellular service provider (CTCarrier carrierName) - `carrier_country` – the ISO country code for the user’s cellular service provider. - App-oriented, including: - `app_name` – the app name - `app_version` – the app version number - `vendor_id` – the unique identifier for app vendor (i.e. UUID string) - `moca_version` – the version of MOCA SDK - `apns_token` – the push notification device token (optional) - `session` – session counter (how many times a user launched the app). - The object may also store any custom property-value pairs. - 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": "#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" }, { "code": "let theInstance = MOCA.currentInstance()\nif (theInstance != nil) {\nlet adId: String = ASIdentifierManager.shared().advertisingIdentifier.uuidString\ntheInstance?.setValue(adId, forProperty: \"_ad_id\")\ntheInstance?.setValue(\"red\", forProperty: \"favorite-color\")\ntheInstance?.setValue(\"women-cloth\", forProperty: \"last-search\")\n// Asynchronously save the instance to the cloud.\ntheInstance?.save({(_ instance: MOCAInstance?, _ error: Error?) -> Void in\nif error != nil {\nprint(\"Save instance failed: (%@)\", error ?? \"Error not available\")\n}\n})\n}", "language": "swift" } ] } [/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": "MOCAInstance * theInstance = [MOCA currentInstance];", "language": "objectivec" }, { "code": "var theInstance = MOCA.currentInstance()", "language": "swift" } ] } [/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- (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" }, { "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" } ] } [/block] [block:callout] { "type": "info", "title": "info", "body": "MOCA properties are internally stored in a local SQLite database" } [/block] The instance object holds predefined properties collected automatically: - `Device-oriented`, including: - `device_model` – the device model (i.e. iPhone 4S, iPhone 5C, iPhone 5S) - `device_type` – the type of device (i.e. iPhone, iPad, Simulator) - `local_timezone` – the local time zone's abbreviated name (i.e. EDT, GMT, PST) - `country` – the country code as defined by the user in `Settings\General\International\Regional Format (NSLocaleCountryCode)`. - `lang` – the user preferred language code as defined in `Settings\General\International\Language (NSLocaleLanguageCode)`. - `os_name` – the OS name (i.e. “iOS”) - `os_version` – the OS version (i.e. “7.0”) - `carrier_name` – the name of the user’s home cellular service provider (CTCarrier carrierName) - `carrier_country` – the ISO country code for the user’s cellular service provider. - App-oriented, including: - `app_name` – the app name - `app_version` – the app version number - `vendor_id` – the unique identifier for app vendor (i.e. UUID string) - `moca_version` – the version of MOCA SDK - `apns_token` – the push notification device token (optional) - `session` – session counter (how many times a user launched the app). - The object may also store any custom property-value pairs. - 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": "#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" }, { "code": "let theInstance = MOCA.currentInstance()\nif (theInstance != nil) {\nlet adId: String = ASIdentifierManager.shared().advertisingIdentifier.uuidString\ntheInstance?.setValue(adId, forProperty: \"_ad_id\")\ntheInstance?.setValue(\"red\", forProperty: \"favorite-color\")\ntheInstance?.setValue(\"women-cloth\", forProperty: \"last-search\")\n// Asynchronously save the instance to the cloud.\ntheInstance?.save({(_ instance: MOCAInstance?, _ error: Error?) -> Void in\nif error != nil {\nprint(\"Save instance failed: (%@)\", error ?? \"Error not available\")\n}\n})\n}", "language": "swift" } ] } [/block]
{"_id":"59198f21eba9ac3100018603","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\": \"// Access authenticated user object\\nMOCAUser * theUser = [[MOCA currentInstance] currentUser];\\nif (theUser)\\n{\\n    // ...\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"let theUser: MOCAUser? = MOCA.currentInstance().currentUser\\nif theUser != nil {\\n// ...\\n}\",\n      \"language\": \"swift\"\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\": \"After launching the app, check whether the user is still logged in or not. If the user is still logged in, perform a new login in the SDK.\",\n  \"title\": \"Login the user with every app startup\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Authenticate a user by e-mail address    \\nMOCAUser * currentUser = [[MOCA currentInstance] login:@\\\"UNIQUE_USER_ID\\\"];\\nif (currentUser)\\n{\\n   // ...\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"// Authenticate a user by e-mail address\\nlet currentUser: MOCAUser? = MOCA.currentInstance().login(\\\"UNIQUE_USER_ID\\\")\\nif currentUser != nil {\\n// ...\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n- To logout a user, call:\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"[theUser logout];\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"theUser.logout()\",\n      \"language\": \"swift\"\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\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAUser * theUser = [[MOCA currentInstance] currentUser];    \\nif (theUser)\\n{\\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      \"code\": \"let theUser: MOCAUser? = MOCA.currentInstance().currentUser\\nif theUser != nil {\\ntheUser.setValue(\\\"male\\\", forProperty: \\\"gender\\\")\\ntheUser.setValue(Int(1975), forProperty: \\\"birth_year\\\")\\n// Asynchronously save the user object to the cloud.\\ntheUser?.save({(_ user: MOCAUser?, _ error: Error?) -> Void in\\n  if error != nil {\\n  print(\\\"Save user failed: (%@)\\\", error ?? \\\"Error not available\\\")\\n  }\\n})\\n}\",\n      \"language\": \"swift\"\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":"59198f1eeba9ac31000185de","__v":0,"excerpt":"","next":{"pages":[],"description":""},"order":2,"type":"basic","category":"59198f20eba9ac31000185e1","link_external":false,"link_url":"","parentDoc":null,"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": "// Access authenticated user object\nMOCAUser * theUser = [[MOCA currentInstance] currentUser];\nif (theUser)\n{\n // ...\n}\n", "language": "objectivec" }, { "code": "let theUser: MOCAUser? = MOCA.currentInstance().currentUser\nif theUser != nil {\n// ...\n}", "language": "swift" } ] } [/block] - To authenticate a new user, use *login:id* call: [block:callout] { "type": "warning", "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 login in the SDK.", "title": "Login the user with every app startup" } [/block] [block:code] { "codes": [ { "code": "// Authenticate a user by e-mail address \nMOCAUser * currentUser = [[MOCA currentInstance] login:@\"UNIQUE_USER_ID\"];\nif (currentUser)\n{\n // ...\n}\n", "language": "objectivec" }, { "code": "// Authenticate a user by e-mail address\nlet currentUser: MOCAUser? = MOCA.currentInstance().login(\"UNIQUE_USER_ID\")\nif currentUser != nil {\n// ...\n}", "language": "swift" } ] } [/block] - To logout a user, call: [block:code] { "codes": [ { "code": "[theUser logout];", "language": "objectivec" }, { "code": "theUser.logout()", "language": "swift" } ] } [/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": "MOCAUser * theUser = [[MOCA currentInstance] currentUser]; \nif (theUser)\n{\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" }, { "code": "let theUser: MOCAUser? = MOCA.currentInstance().currentUser\nif theUser != nil {\ntheUser.setValue(\"male\", forProperty: \"gender\")\ntheUser.setValue(Int(1975), forProperty: \"birth_year\")\n// Asynchronously save the user object to the cloud.\ntheUser?.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" } ] } [/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": "// Access authenticated user object\nMOCAUser * theUser = [[MOCA currentInstance] currentUser];\nif (theUser)\n{\n // ...\n}\n", "language": "objectivec" }, { "code": "let theUser: MOCAUser? = MOCA.currentInstance().currentUser\nif theUser != nil {\n// ...\n}", "language": "swift" } ] } [/block] - To authenticate a new user, use *login:id* call: [block:callout] { "type": "warning", "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 login in the SDK.", "title": "Login the user with every app startup" } [/block] [block:code] { "codes": [ { "code": "// Authenticate a user by e-mail address \nMOCAUser * currentUser = [[MOCA currentInstance] login:@\"UNIQUE_USER_ID\"];\nif (currentUser)\n{\n // ...\n}\n", "language": "objectivec" }, { "code": "// Authenticate a user by e-mail address\nlet currentUser: MOCAUser? = MOCA.currentInstance().login(\"UNIQUE_USER_ID\")\nif currentUser != nil {\n// ...\n}", "language": "swift" } ] } [/block] - To logout a user, call: [block:code] { "codes": [ { "code": "[theUser logout];", "language": "objectivec" }, { "code": "theUser.logout()", "language": "swift" } ] } [/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": "MOCAUser * theUser = [[MOCA currentInstance] currentUser]; \nif (theUser)\n{\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" }, { "code": "let theUser: MOCAUser? = MOCA.currentInstance().currentUser\nif theUser != nil {\ntheUser.setValue(\"male\", forProperty: \"gender\")\ntheUser.setValue(Int(1975), forProperty: \"birth_year\")\n// Asynchronously save the user object to the cloud.\ntheUser?.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" } ] } [/block]
{"_id":"59198f21eba9ac3100018604","excerpt":"","link_external":false,"slug":"user-profile","updates":[],"__v":0,"githubsync":"","isReference":false,"link_url":"","type":"basic","api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required"},"createdAt":"2015-07-17T13:30:01.589Z","order":3,"title":"User Profile","user":"559a618bdbcfd20d00710b38","version":"59198f1eeba9ac31000185de","body":"- The MOCA SDK, once the user has opted in, passively develops \u000ba *User Profile* of mobile usage and other behaviors.\n- The profile ensures that the app can deliver much more personalized, relevant content based on: \n - Interests – sports, video games, books, cooking\n - Places of Interests (POIs) – top locations where the user spends time (e.g. home, work, restaurant, etc.)\n- User profile is elaborated automatically without user interaction\n- MOCA respects user’s privacy. Contact us for privacy policy recommendations.","hidden":false,"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","sync_unique":"","category":"59198f20eba9ac31000185e1","next":{"pages":[],"description":""},"childrenPages":[]}

User Profile


- The MOCA SDK, once the user has opted in, passively develops a *User Profile* of mobile usage and other behaviors. - The profile ensures that the app can deliver much more personalized, relevant content based on: - Interests – sports, video games, books, cooking - Places of Interests (POIs) – top locations where the user spends time (e.g. home, work, restaurant, etc.) - User profile is elaborated automatically without user interaction - MOCA respects user’s privacy. Contact us for privacy policy recommendations.
- The MOCA SDK, once the user has opted in, passively develops a *User Profile* of mobile usage and other behaviors. - The profile ensures that the app can deliver much more personalized, relevant content based on: - Interests – sports, video games, books, cooking - Places of Interests (POIs) – top locations where the user spends time (e.g. home, work, restaurant, etc.) - User profile is elaborated automatically without user interaction - MOCA respects user’s privacy. Contact us for privacy policy recommendations.
{"_id":"59198f21eba9ac3100018605","__v":0,"category":"59198f20eba9ac31000185e1","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":"59198f1eeba9ac31000185de","isReference":false,"link_external":false,"order":4,"sync_unique":"","user":"559a618bdbcfd20d00710b38","body":"# Introduction\n\n\n- 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- 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","childrenPages":[]}

Tag API


# Introduction - 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. - 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 - 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. - 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":"59198f21eba9ac3100018606","link_external":false,"order":5,"sync_unique":"","title":"Segments","hidden":false,"isReference":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","__v":0,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"code":"{}","language":"json","status":400,"name":""}]},"settings":"","auth":"required","params":[],"url":""},"category":"59198f20eba9ac31000185e1","excerpt":"","version":"59198f1eeba9ac31000185de","updates":[],"user":"559a618bdbcfd20d00710b38","createdAt":"2015-07-17T13:35:19.155Z","githubsync":"","next":{"pages":[],"description":""},"body":"- To describe segments the user belongs to, MOCA uses `Segment objects`. Segments are *predefined* items of information with well defined semantics for the given data provider. \n\n- The segment objects allow data about the anonymous user (i.e. MOCA Instance) or logged-in user (MOCA User) to be passed to Ad services in order to improve *Ad targeting.*\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/Gf9PO6b5TKikNu229Hq6_Algorithm.png\",\n        \"Algorithm.png\",\n        \"875\",\n        \"547\",\n        \"#2c95d4\",\n        \"\"\n      ],\n      \"caption\": \"Profile Sensing\"\n    }\n  ]\n}\n[/block]","parentDoc":null,"slug":"segments-1","type":"basic","childrenPages":[]}

Segments


- To describe segments the user belongs to, MOCA uses `Segment objects`. Segments are *predefined* items of information with well defined semantics for the given data provider. - The segment objects allow data about the anonymous user (i.e. MOCA Instance) or logged-in user (MOCA User) to be passed to Ad services in order to improve *Ad targeting.* [block:image] { "images": [ { "image": [ "https://files.readme.io/Gf9PO6b5TKikNu229Hq6_Algorithm.png", "Algorithm.png", "875", "547", "#2c95d4", "" ], "caption": "Profile Sensing" } ] } [/block]
- To describe segments the user belongs to, MOCA uses `Segment objects`. Segments are *predefined* items of information with well defined semantics for the given data provider. - The segment objects allow data about the anonymous user (i.e. MOCA Instance) or logged-in user (MOCA User) to be passed to Ad services in order to improve *Ad targeting.* [block:image] { "images": [ { "image": [ "https://files.readme.io/Gf9PO6b5TKikNu229Hq6_Algorithm.png", "Algorithm.png", "875", "547", "#2c95d4", "" ], "caption": "Profile Sensing" } ] } [/block]
{"_id":"59198f21eba9ac3100018607","updates":[],"api":{"auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":""},"category":"59198f20eba9ac31000185e1","isReference":false,"link_url":"","order":6,"hidden":false,"excerpt":"","githubsync":"","slug":"event-tracking","type":"basic","version":"59198f1eeba9ac31000185de","next":{"pages":[],"description":""},"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","__v":0,"body":"- The `Event object` enables you to feed data to MOCA Analytics. \n- The Event API *captures and transmits* to the cloud the *flow of arbitrary* events associated with the app.\n- A single event object represents the *record* that indicates that *something has happened*.\n - Such as App started, Push notification received, Beacon detected, etc.\n- There are two types of events: \n - Predefined – tracked automatically by the SDK\n - Custom – tracked by the app","createdAt":"2015-07-17T13:39:38.644Z","link_external":false,"sync_unique":"","title":"Event tracking","user":"559a618bdbcfd20d00710b38","childrenPages":[]}

Event tracking


- The `Event object` enables you to feed data to MOCA Analytics. - The Event API *captures and transmits* to the cloud the *flow of arbitrary* events associated with the app. - A single event object represents the *record* that indicates that *something has happened*. - Such as App started, Push notification received, Beacon detected, etc. - There are two types of events: - Predefined – tracked automatically by the SDK - Custom – tracked by the app
- The `Event object` enables you to feed data to MOCA Analytics. - The Event API *captures and transmits* to the cloud the *flow of arbitrary* events associated with the app. - A single event object represents the *record* that indicates that *something has happened*. - Such as App started, Push notification received, Beacon detected, etc. - There are two types of events: - Predefined – tracked automatically by the SDK - Custom – tracked by the app
{"_id":"59198f21eba9ac3100018608","project":"559a61d2dbcfd20d00710b39","slug":"event-api","user":"559a618bdbcfd20d00710b38","githubsync":"","isReference":false,"parentDoc":null,"body":"A single `event object` record contains:\n\n- Event data:\n - Identifier – unique event ID (UUID)\n - Timestamp – GMT timestamp when the event occurred\n - Local timestamp – timestamp with local timezone\n - Event type – type of event\n - Action verb – string that describes performed action (i.e. Buy, View, Search, Enter, etc.)\n - Item – item associated with the event (i.e. Product ID)\n - Item Category – category the item belongs to (Product Category)\n - Value – value associated with the event (E.g. purchase amount)\n\n- Context data:\n - Instance ID – the instance object ID that generated the event\n - User ID – the logged-in user that generated the event (optional)\n - Device model/type\n - OS name/version\n - Country\n - Language\n - And other attributes\n\nBy default, the SDK automatically tracks predefined events:\n - _start_session – when the new app session was started\n - _session – when the user’s session ends\n - _geo – track last coordinates of the current location *\n - _visit – when a user visits a frequent place *\n - _push – when push notification has been received while the app was running\n - _launching_push – when app was started by a push notification\n - _action – when proximity action has been triggered\n - _beacon_proximity – when the device entered/exited a beacon region *\n - _zone_proximity – when the device entered/exited a proximity zone *\n - _place_proximity – when the device entered/exited a proximity place *\n - _tick – indicates if the app is active\n - _user_login – when user logged in\n - _user_logout – when user logged out\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"* Used when available and allowed by user privacy settings.\"\n}\n[/block]\nTo track custom events in your app, use the following API:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\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>YES</code> in case of success, <code>NO</code> in case of error.\\n */\\n+ (BOOL) track:(NSString*)verb;\\n\\n/**\\n * Track event helper methods. \\n */\\n+ (BOOL) track:(NSString*)verb withValue:(NSNumber*)value;\\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item;\\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item withValue:(NSNumber*)value;\\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category;\\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category withValue:(NSNumber*)value;\\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category withIntValue:(int)value;\\n\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"/**\\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>YES</code> in case of success, <code>NO</code> in case of error.\\n*/\\n\\nclass func track(_ verb: String) -> Bool \\n\\n/**\\n* Track event helper methods. \\n*/\\nclass func track(_ verb: String, withValue value: NSNumber) -> Bool \\n\\nclass func track(_ verb: String, forItem item: String) -> Bool \\n\\nclass func track(_ verb: String, forItem item: String, withValue value: NSNumber) -> Bool \\n\\nclass func track(_ verb: String, forItem item: String, belongingTo category: String) -> Bool \\n\\nclass func track(_ verb: String, forItem item: String, belongingTo category: String, withValue value: NSNumber) -> Bool\\n\\nclass func track(_ verb: String, forItem item: String, belongingTo category: String, withIntValue value: Int) -> Bool\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\nCustom tracking example:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender\\n{\\n    if ([[segue identifier] isEqualToString:@”ViewProduct\\\"])\\n    {\\n      NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];\\n \\tProduct *product = self.products [indexPath];\\n\\t// Track view product event\\n        [MOCAEvent track:@”view” forItem:product.id];\\n    }\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"func prepare(for segue: UIStoryboardSegue, sender: Any?){\\n  if (segue.identifier == \\\"ViewProduct\\\" ) {\\n  let indexPath = tableView.indexPathForSelectedRow()\\n    let product = products[indexPath]\\n    // Track view product event\\n    MOCAEvent.track(\\\"view\\\", forItem: product?.id)\\n   }\\n}\\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]","createdAt":"2015-07-17T13:43:01.255Z","next":{"pages":[],"description":""},"excerpt":"","link_external":false,"link_url":"","order":7,"sync_unique":"","__v":0,"api":{"results":{"codes":[{"code":"{}","language":"json","status":200,"name":""},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"version":"59198f1eeba9ac31000185de","type":"basic","updates":[],"category":"59198f20eba9ac31000185e1","hidden":false,"title":"Event API","childrenPages":[]}

Event API


A single `event object` record contains: - Event data: - Identifier – unique event ID (UUID) - Timestamp – GMT timestamp when the event occurred - Local timestamp – timestamp with local timezone - Event type – type of event - Action verb – string that describes performed action (i.e. Buy, View, Search, Enter, etc.) - Item – item associated with the event (i.e. Product ID) - Item Category – category the item belongs to (Product Category) - Value – value associated with the event (E.g. purchase amount) - Context data: - Instance ID – the instance object ID that generated the event - User ID – the logged-in user that generated the event (optional) - Device model/type - OS name/version - Country - Language - And other attributes By default, the SDK automatically tracks predefined events: - _start_session – when the new app session was started - _session – when the user’s session ends - _geo – track last coordinates of the current location * - _visit – when a user visits a frequent place * - _push – when push notification has been received while the app was running - _launching_push – when app was started by a push notification - _action – when proximity action has been triggered - _beacon_proximity – when the device entered/exited a beacon region * - _zone_proximity – when the device entered/exited a proximity zone * - _place_proximity – when the device entered/exited a proximity place * - _tick – indicates if the app is active - _user_login – when user logged in - _user_logout – when user logged out [block:callout] { "type": "warning", "body": "* Used when available and allowed by user privacy settings." } [/block] To track custom events in your app, use the following API: [block:code] { "codes": [ { "code": "/**\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>YES</code> in case of success, <code>NO</code> in case of error.\n */\n+ (BOOL) track:(NSString*)verb;\n\n/**\n * Track event helper methods. \n */\n+ (BOOL) track:(NSString*)verb withValue:(NSNumber*)value;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item withValue:(NSNumber*)value;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category withValue:(NSNumber*)value;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category withIntValue:(int)value;\n\n", "language": "objectivec" }, { "code": "/**\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>YES</code> in case of success, <code>NO</code> in case of error.\n*/\n\nclass func track(_ verb: String) -> Bool \n\n/**\n* Track event helper methods. \n*/\nclass func track(_ verb: String, withValue value: NSNumber) -> Bool \n\nclass func track(_ verb: String, forItem item: String) -> Bool \n\nclass func track(_ verb: String, forItem item: String, withValue value: NSNumber) -> Bool \n\nclass func track(_ verb: String, forItem item: String, belongingTo category: String) -> Bool \n\nclass func track(_ verb: String, forItem item: String, belongingTo category: String, withValue value: NSNumber) -> Bool\n\nclass func track(_ verb: String, forItem item: String, belongingTo category: String, withIntValue value: Int) -> Bool", "language": "swift" } ] } [/block] Custom tracking example: [block:code] { "codes": [ { "code": "(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender\n{\n if ([[segue identifier] isEqualToString:@”ViewProduct\"])\n {\n NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];\n \tProduct *product = self.products [indexPath];\n\t// Track view product event\n [MOCAEvent track:@”view” forItem:product.id];\n }\n}\n", "language": "objectivec" }, { "code": "func prepare(for segue: UIStoryboardSegue, sender: Any?){\n if (segue.identifier == \"ViewProduct\" ) {\n let indexPath = tableView.indexPathForSelectedRow()\n let product = products[indexPath]\n // Track view product event\n MOCAEvent.track(\"view\", forItem: product?.id)\n }\n}\n", "language": "swift" } ] } [/block]
A single `event object` record contains: - Event data: - Identifier – unique event ID (UUID) - Timestamp – GMT timestamp when the event occurred - Local timestamp – timestamp with local timezone - Event type – type of event - Action verb – string that describes performed action (i.e. Buy, View, Search, Enter, etc.) - Item – item associated with the event (i.e. Product ID) - Item Category – category the item belongs to (Product Category) - Value – value associated with the event (E.g. purchase amount) - Context data: - Instance ID – the instance object ID that generated the event - User ID – the logged-in user that generated the event (optional) - Device model/type - OS name/version - Country - Language - And other attributes By default, the SDK automatically tracks predefined events: - _start_session – when the new app session was started - _session – when the user’s session ends - _geo – track last coordinates of the current location * - _visit – when a user visits a frequent place * - _push – when push notification has been received while the app was running - _launching_push – when app was started by a push notification - _action – when proximity action has been triggered - _beacon_proximity – when the device entered/exited a beacon region * - _zone_proximity – when the device entered/exited a proximity zone * - _place_proximity – when the device entered/exited a proximity place * - _tick – indicates if the app is active - _user_login – when user logged in - _user_logout – when user logged out [block:callout] { "type": "warning", "body": "* Used when available and allowed by user privacy settings." } [/block] To track custom events in your app, use the following API: [block:code] { "codes": [ { "code": "/**\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>YES</code> in case of success, <code>NO</code> in case of error.\n */\n+ (BOOL) track:(NSString*)verb;\n\n/**\n * Track event helper methods. \n */\n+ (BOOL) track:(NSString*)verb withValue:(NSNumber*)value;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item withValue:(NSNumber*)value;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category withValue:(NSNumber*)value;\n+ (BOOL) track:(NSString*)verb forItem:(NSString*)item belongingTo:(NSString*)category withIntValue:(int)value;\n\n", "language": "objectivec" }, { "code": "/**\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>YES</code> in case of success, <code>NO</code> in case of error.\n*/\n\nclass func track(_ verb: String) -> Bool \n\n/**\n* Track event helper methods. \n*/\nclass func track(_ verb: String, withValue value: NSNumber) -> Bool \n\nclass func track(_ verb: String, forItem item: String) -> Bool \n\nclass func track(_ verb: String, forItem item: String, withValue value: NSNumber) -> Bool \n\nclass func track(_ verb: String, forItem item: String, belongingTo category: String) -> Bool \n\nclass func track(_ verb: String, forItem item: String, belongingTo category: String, withValue value: NSNumber) -> Bool\n\nclass func track(_ verb: String, forItem item: String, belongingTo category: String, withIntValue value: Int) -> Bool", "language": "swift" } ] } [/block] Custom tracking example: [block:code] { "codes": [ { "code": "(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender\n{\n if ([[segue identifier] isEqualToString:@”ViewProduct\"])\n {\n NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];\n \tProduct *product = self.products [indexPath];\n\t// Track view product event\n [MOCAEvent track:@”view” forItem:product.id];\n }\n}\n", "language": "objectivec" }, { "code": "func prepare(for segue: UIStoryboardSegue, sender: Any?){\n if (segue.identifier == \"ViewProduct\" ) {\n let indexPath = tableView.indexPathForSelectedRow()\n let product = products[indexPath]\n // Track view product event\n MOCAEvent.track(\"view\", forItem: product?.id)\n }\n}\n", "language": "swift" } ] } [/block]
{"_id":"59198f21eba9ac3100018609","excerpt":"MOCA SDK easily integrates with iOS push notifications.","githubsync":"","updates":[],"user":"559a618bdbcfd20d00710b38","createdAt":"2015-07-17T13:47:07.890Z","link_url":"","project":"559a61d2dbcfd20d00710b39","sync_unique":"","type":"basic","order":8,"parentDoc":null,"version":"59198f1eeba9ac31000185de","api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"body":"##Features\n\n- Push notification registration\n - Automatic - configure MOCA SDK to register your app for remote push notifications.\n - Manual – handle remote push notification registration from your app and only register deviceToken in the  SDK \n- Push notification tracking\n - Tracked received push notifications with MOCA SDK. \n - The tracked data can be analyzed in MOCA Analytics (Pushes, PushOpened, and more).\n\n##Integration\n\nTo use automatic push notifications registration in MOCA, you’ll need to enable push service.\n\n1. Ensure automatic push setup is enabled in MOCAConfig.plist file.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/YSZRxxoGS6qEegXyCQg8_push.png\",\n        \"push.png\",\n        \"587\",\n        \"245\",\n        \"#3e5077\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n2 . The `[MOCA initializeSDK] `call will register for remote push notification for you:\n\n- For iOS7: `[[UIApplication sharedApplication] registerForRemoteNotificationTypes:] `\n- For iOS8+:` [[UIApplication sharedApplication] registerUserNotificationSettings:]` and  `[[UIApplication sharedApplication] registerForRemoteNotifications:] ` \n\n\n3. Next, implement `[didRegisterForRemoteNotificationsWithDeviceToken:]` app delegate callback:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken\\n{\\n    NSLog(@\\\"APNS token: %@\\\", deviceToken);\\n    // Register push token in MOCA\\n    [MOCA registerDeviceToken:deviceToken];\\n}\",\n      \"language\": \"objectivec\",\n      \"name\": \"Send received push token to MOCA Cloud\"\n    },\n    {\n      \"code\": \"func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\\nprint(\\\"APNS token: \\\\(deviceToken)\\\");\\n// Register push token in MOCA\\nMOCA.registerDeviceToken(deviceToken)\\n}\\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\nAnd handle errors through the following callback.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\\n{\\n   // Handle error\\n  NSLog(@\\\"Push notifications registration failed 😨\\\");\\n}\\n\",\n      \"language\": \"objectivec\",\n      \"name\": \"Handle registration errors\"\n    },\n    {\n      \"code\": \"//Called after user taps a notification\\n\\nfunc application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\\n// Handle error\\nprint(\\\"Push notifications registration failed \\\")\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n4.  Complete, the process by implementing the app delegate callbacks:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"//Called after user taps a notification\\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\\n{\\n    if (MOCA.initialized) {\\n        [MOCA handleLocalNotification:notification];\\n    }  \\n}\\n\\n//Called when the remote push notification is received from the server\\n-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{\\n    \\n    if (MOCA.initialized) {\\n        [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:completionHandler];\\n    }\\n}\\n\",\n      \"language\": \"objectivec\",\n      \"name\": \"Handle remote notifications\"\n    },\n    {\n      \"code\": \"//Called after user taps a notification\\n\\nfunc application(_ application: UIApplication, didReceive notification: UILocalNotification) {\\n  if MOCA.initialized() {\\n  MOCA.handle(notification)\\n  }\\n}\\n\\n//Called when the remote push notification is received from the server\\nfunc 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      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]","category":"59198f20eba9ac31000185e1","hidden":false,"next":{"pages":[],"description":""},"__v":0,"isReference":false,"link_external":false,"slug":"push-api","title":"Push API","childrenPages":[]}

Push API

MOCA SDK easily integrates with iOS push notifications.

##Features - Push notification registration - Automatic - configure MOCA SDK to register your app for remote push notifications. - Manual – handle remote push notification registration from your app and only register deviceToken in the SDK - Push notification tracking - Tracked received push notifications with MOCA SDK. - The tracked data can be analyzed in MOCA Analytics (Pushes, PushOpened, and more). ##Integration To use automatic push notifications registration in MOCA, you’ll need to enable push service. 1. Ensure automatic push setup is enabled in MOCAConfig.plist file. [block:image] { "images": [ { "image": [ "https://files.readme.io/YSZRxxoGS6qEegXyCQg8_push.png", "push.png", "587", "245", "#3e5077", "" ] } ] } [/block] 2 . The `[MOCA initializeSDK] `call will register for remote push notification for you: - For iOS7: `[[UIApplication sharedApplication] registerForRemoteNotificationTypes:] ` - For iOS8+:` [[UIApplication sharedApplication] registerUserNotificationSettings:]` and `[[UIApplication sharedApplication] registerForRemoteNotifications:] ` 3. Next, implement `[didRegisterForRemoteNotificationsWithDeviceToken:]` app delegate callback: [block:code] { "codes": [ { "code": "- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken\n{\n NSLog(@\"APNS token: %@\", deviceToken);\n // Register push token in MOCA\n [MOCA registerDeviceToken:deviceToken];\n}", "language": "objectivec", "name": "Send received push token to MOCA Cloud" }, { "code": "func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\nprint(\"APNS token: \\(deviceToken)\");\n// Register push token in MOCA\nMOCA.registerDeviceToken(deviceToken)\n}\n", "language": "swift" } ] } [/block] And handle errors through the following callback. [block:code] { "codes": [ { "code": "- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\n{\n // Handle error\n NSLog(@\"Push notifications registration failed 😨\");\n}\n", "language": "objectivec", "name": "Handle registration errors" }, { "code": "//Called after user taps a notification\n\nfunc application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n// Handle error\nprint(\"Push notifications registration failed \")\n}", "language": "swift" } ] } [/block] 4. Complete, the process by implementing the app delegate callbacks: [block:code] { "codes": [ { "code": "//Called after user taps a notification\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\n{\n if (MOCA.initialized) {\n [MOCA handleLocalNotification:notification];\n } \n}\n\n//Called when the remote push notification is received from the server\n-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{\n \n if (MOCA.initialized) {\n [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:completionHandler];\n }\n}\n", "language": "objectivec", "name": "Handle remote notifications" }, { "code": "//Called after user taps a notification\n\nfunc application(_ application: UIApplication, didReceive notification: UILocalNotification) {\n if MOCA.initialized() {\n MOCA.handle(notification)\n }\n}\n\n//Called when the remote push notification is received from the server\nfunc application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\n}\n}", "language": "swift" } ] } [/block]
##Features - Push notification registration - Automatic - configure MOCA SDK to register your app for remote push notifications. - Manual – handle remote push notification registration from your app and only register deviceToken in the SDK - Push notification tracking - Tracked received push notifications with MOCA SDK. - The tracked data can be analyzed in MOCA Analytics (Pushes, PushOpened, and more). ##Integration To use automatic push notifications registration in MOCA, you’ll need to enable push service. 1. Ensure automatic push setup is enabled in MOCAConfig.plist file. [block:image] { "images": [ { "image": [ "https://files.readme.io/YSZRxxoGS6qEegXyCQg8_push.png", "push.png", "587", "245", "#3e5077", "" ] } ] } [/block] 2 . The `[MOCA initializeSDK] `call will register for remote push notification for you: - For iOS7: `[[UIApplication sharedApplication] registerForRemoteNotificationTypes:] ` - For iOS8+:` [[UIApplication sharedApplication] registerUserNotificationSettings:]` and `[[UIApplication sharedApplication] registerForRemoteNotifications:] ` 3. Next, implement `[didRegisterForRemoteNotificationsWithDeviceToken:]` app delegate callback: [block:code] { "codes": [ { "code": "- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken\n{\n NSLog(@\"APNS token: %@\", deviceToken);\n // Register push token in MOCA\n [MOCA registerDeviceToken:deviceToken];\n}", "language": "objectivec", "name": "Send received push token to MOCA Cloud" }, { "code": "func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\nprint(\"APNS token: \\(deviceToken)\");\n// Register push token in MOCA\nMOCA.registerDeviceToken(deviceToken)\n}\n", "language": "swift" } ] } [/block] And handle errors through the following callback. [block:code] { "codes": [ { "code": "- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error\n{\n // Handle error\n NSLog(@\"Push notifications registration failed 😨\");\n}\n", "language": "objectivec", "name": "Handle registration errors" }, { "code": "//Called after user taps a notification\n\nfunc application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n// Handle error\nprint(\"Push notifications registration failed \")\n}", "language": "swift" } ] } [/block] 4. Complete, the process by implementing the app delegate callbacks: [block:code] { "codes": [ { "code": "//Called after user taps a notification\n- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification\n{\n if (MOCA.initialized) {\n [MOCA handleLocalNotification:notification];\n } \n}\n\n//Called when the remote push notification is received from the server\n-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{\n \n if (MOCA.initialized) {\n [MOCA handleRemoteNotification:userInfo fetchCompletionHandler:completionHandler];\n }\n}\n", "language": "objectivec", "name": "Handle remote notifications" }, { "code": "//Called after user taps a notification\n\nfunc application(_ application: UIApplication, didReceive notification: UILocalNotification) {\n if MOCA.initialized() {\n MOCA.handle(notification)\n }\n}\n\n//Called when the remote push notification is received from the server\nfunc application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {\n if MOCA.initialized() {\n MOCA.handleRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)\n}\n}", "language": "swift" } ] } [/block]
{"_id":"59198f21eba9ac310001860a","hidden":false,"order":9,"parentDoc":null,"type":"basic","updates":[],"user":"559a618bdbcfd20d00710b38","__v":0,"api":{"params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required"},"body":"##Introduction\n\n- The *MOCA SDK* lets you effortlessly add Bluetooth beacon based proximity experiences to your iOS app.\n- The SDK comes with a powerful proximity engine based on Complex Event Processing logic (see CEP).\n- MOCA defines some fundamental concepts:\n - Place, Zone, and Beacon\n - Trigger and Action\n - Visit\n\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/4l1tE04pR5uVKvpaeDv6_Da-proximity-experience.png\",\n        \"Da-proximity-experience.png\",\n        \"911\",\n        \"457\",\n        \"#3ba0da\",\n        \"\"\n      ],\n      \"caption\": \"To map real-world context, MOCA introduces some fundamental concepts.\"\n    }\n  ]\n}\n[/block]\nTo start using Bluetooth beacon-based proximity experiences in your app, you’ll need to enable proximity service.\n\n1. Ensure proximity service is enabled in MOCAConfig.plist file.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/pxJrwqaqT5yKS1r1VbqO_proximity-service.png\",\n        \"proximity-service.png\",\n        \"587\",\n        \"245\",\n        \"#425479\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n2. The `[MOCA initializeSDK]` call will automatically start MOCA proximity engine and synchronize proximity campaigns defined in your MOCA cloud account.\n\n###Places\nRepresents a real-world locations, such as a store, venue, museum, building, office and so on.\n- A place can be localized by a geo-fence (GPS location and radius in meters) \n- A place contains a collection of zones, where each zone defines semantics for an indoor location, such as Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc.\n\n###Zone\nRepresents a indoor area or micro-location within the place with user-defined semantics. \n- Examples include ds Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc.\n- A zone is defined by a range of one or more beacon sensors. \n\n###Beacon\nIt is a BLE, iBeacon-compatible proximity sensor.\n- Each beacon is identified by { Proximity UUID, Major and Minor } tuple.\n- MOCA SDK works with any iBeacon-compatible devices. \n - This includes MOCA Beacons \n - And beacons provided by other manufacturers such as Kontakt.io, Estimote, etc.\n- Beacons are assigned to Zones that define their micro-location semantics. \n- Each beacon must be registered in MOCA Management Console.\n\n###Campaigns \nCollections of proximity experiences that are delivered to a user within a specified time frame.\n\n###Experience \nDefines a proximity interaction with a user. \n- An experience is composed of a trigger condition and an action. \n- When proximity trigger conditions are met, the corresponding action is fired.\n\n###Trigger\nIt is a condition or a collection of conditions that must be met to fire an action associated with an experience. For example:\n- Enter place, \n- Exit place, \n- Enter zone, \n- Exit zone,\n- Enter beacon range with given proximity, \n- Exit beacon range\n- Custom trigger (implemented as app-provided delegate callback)\n\n###Action\nDescribes an activity to be performed when experience trigger conditions are met. The SDK supports the following actions:\n- Show local push notification with a specific message\n- Play sound with a specific file name (included in app bundle)\n- Play video from URL\n- Show image from URL\n- Show HTML content from URL\n- Open custom URL\n- Show PassBook card\n- Custom action (implemented as app-provided delegate callback)\n\n\nThe SDK provides delegates that enable full customization of all performed actions. \u000b\tSee `MOCAProximityActionsDelegate` in `MOCAProximityDelegate.h` file for details.","category":"59198f20eba9ac31000185e1","title":"Proximity API","isReference":false,"link_url":"","next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","version":"59198f1eeba9ac31000185de","slug":"proximity-api","sync_unique":"","createdAt":"2015-07-17T13:54:17.291Z","excerpt":"","githubsync":"","link_external":false,"childrenPages":[]}

Proximity API


##Introduction - The *MOCA SDK* lets you effortlessly add Bluetooth beacon based proximity experiences to your iOS app. - The SDK comes with a powerful proximity engine based on Complex Event Processing logic (see CEP). - MOCA defines some fundamental concepts: - Place, Zone, and Beacon - Trigger and Action - Visit [block:image] { "images": [ { "image": [ "https://files.readme.io/4l1tE04pR5uVKvpaeDv6_Da-proximity-experience.png", "Da-proximity-experience.png", "911", "457", "#3ba0da", "" ], "caption": "To map real-world context, MOCA introduces some fundamental concepts." } ] } [/block] To start using Bluetooth beacon-based proximity experiences in your app, you’ll need to enable proximity service. 1. Ensure proximity service is enabled in MOCAConfig.plist file. [block:image] { "images": [ { "image": [ "https://files.readme.io/pxJrwqaqT5yKS1r1VbqO_proximity-service.png", "proximity-service.png", "587", "245", "#425479", "" ] } ] } [/block] 2. The `[MOCA initializeSDK]` call will automatically start MOCA proximity engine and synchronize proximity campaigns defined in your MOCA cloud account. ###Places Represents a real-world locations, such as a store, venue, museum, building, office and so on. - A place can be localized by a geo-fence (GPS location and radius in meters) - A place contains a collection of zones, where each zone defines semantics for an indoor location, such as Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. ###Zone Represents a indoor area or micro-location within the place with user-defined semantics. - Examples include ds Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. - A zone is defined by a range of one or more beacon sensors. ###Beacon It is a BLE, iBeacon-compatible proximity sensor. - Each beacon is identified by { Proximity UUID, Major and Minor } tuple. - MOCA SDK works with any iBeacon-compatible devices. - This includes MOCA Beacons - And beacons provided by other manufacturers such as Kontakt.io, Estimote, etc. - Beacons are assigned to Zones that define their micro-location semantics. - Each beacon must be registered in MOCA Management Console. ###Campaigns Collections of proximity experiences that are delivered to a user within a specified time frame. ###Experience Defines a proximity interaction with a user. - An experience is composed of a trigger condition and an action. - When proximity trigger conditions are met, the corresponding action is fired. ###Trigger It is a condition or a collection of conditions that must be met to fire an action associated with an experience. For example: - Enter place, - Exit place, - Enter zone, - Exit zone, - Enter beacon range with given proximity, - Exit beacon range - Custom trigger (implemented as app-provided delegate callback) ###Action Describes an activity to be performed when experience trigger conditions are met. The SDK supports the following actions: - Show local push notification with a specific message - Play sound with a specific file name (included in app bundle) - Play video from URL - Show image from URL - Show HTML content from URL - Open custom URL - Show PassBook card - Custom action (implemented as app-provided delegate callback) The SDK provides delegates that enable full customization of all performed actions. See `MOCAProximityActionsDelegate` in `MOCAProximityDelegate.h` file for details.
##Introduction - The *MOCA SDK* lets you effortlessly add Bluetooth beacon based proximity experiences to your iOS app. - The SDK comes with a powerful proximity engine based on Complex Event Processing logic (see CEP). - MOCA defines some fundamental concepts: - Place, Zone, and Beacon - Trigger and Action - Visit [block:image] { "images": [ { "image": [ "https://files.readme.io/4l1tE04pR5uVKvpaeDv6_Da-proximity-experience.png", "Da-proximity-experience.png", "911", "457", "#3ba0da", "" ], "caption": "To map real-world context, MOCA introduces some fundamental concepts." } ] } [/block] To start using Bluetooth beacon-based proximity experiences in your app, you’ll need to enable proximity service. 1. Ensure proximity service is enabled in MOCAConfig.plist file. [block:image] { "images": [ { "image": [ "https://files.readme.io/pxJrwqaqT5yKS1r1VbqO_proximity-service.png", "proximity-service.png", "587", "245", "#425479", "" ] } ] } [/block] 2. The `[MOCA initializeSDK]` call will automatically start MOCA proximity engine and synchronize proximity campaigns defined in your MOCA cloud account. ###Places Represents a real-world locations, such as a store, venue, museum, building, office and so on. - A place can be localized by a geo-fence (GPS location and radius in meters) - A place contains a collection of zones, where each zone defines semantics for an indoor location, such as Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. ###Zone Represents a indoor area or micro-location within the place with user-defined semantics. - Examples include ds Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. - A zone is defined by a range of one or more beacon sensors. ###Beacon It is a BLE, iBeacon-compatible proximity sensor. - Each beacon is identified by { Proximity UUID, Major and Minor } tuple. - MOCA SDK works with any iBeacon-compatible devices. - This includes MOCA Beacons - And beacons provided by other manufacturers such as Kontakt.io, Estimote, etc. - Beacons are assigned to Zones that define their micro-location semantics. - Each beacon must be registered in MOCA Management Console. ###Campaigns Collections of proximity experiences that are delivered to a user within a specified time frame. ###Experience Defines a proximity interaction with a user. - An experience is composed of a trigger condition and an action. - When proximity trigger conditions are met, the corresponding action is fired. ###Trigger It is a condition or a collection of conditions that must be met to fire an action associated with an experience. For example: - Enter place, - Exit place, - Enter zone, - Exit zone, - Enter beacon range with given proximity, - Exit beacon range - Custom trigger (implemented as app-provided delegate callback) ###Action Describes an activity to be performed when experience trigger conditions are met. The SDK supports the following actions: - Show local push notification with a specific message - Play sound with a specific file name (included in app bundle) - Play video from URL - Show image from URL - Show HTML content from URL - Open custom URL - Show PassBook card - Custom action (implemented as app-provided delegate callback) The SDK provides delegates that enable full customization of all performed actions. See `MOCAProximityActionsDelegate` in `MOCAProximityDelegate.h` file for details.
{"_id":"59907da2c58f39002d833120","project":"559a61d2dbcfd20d00710b39","version":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e1","user":"559a618bdbcfd20d00710b38","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-08-13T16:26:10.675Z","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":10,"body":"Through the MOCA Indoor Location API, mobile applications are able get their current location indoors with GPS-grade accuracy.\nLocation is provided by using and combining signals from a variety of sensors, including Bluetooth, Wi-Fi or Microelectromechanical systems (Gyroscope, Compass, and Accelerometer).\n\nMOCA SDK relies on 3rd party software to calculate the device location. MOCA SDK for iOS includes  the necessary dependency into the static library. If you want to use this API, you will need to replace your `libMOCALib.a` with the following:\n\n##Indoor Enabled MOCA SDKs for iOS:\n\n- MOCA SDK + NAO SDK v2.4.3n: [link](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/nao/moca-ios-sdk-v2.4.3n.zip) \n_(latest update: 2018-01-14)_\n\n##Changelog\n\nv2.3.3 / v2.3.3n\n- Allow set the location permission strategy property in the Config object.\n- Check if beacon setting is enabled before starting to range beacons\n- Added an error message when trying to create an indoor client without the NAO Dependency available.\n\n\nNAO is a trademark from PoleStar SA. Learn more about PoleStar solutions at [http://www.polestar.eu/](http://www.polestar.eu/)\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"body\": \"You will need an account with PoleStar in order to use this feature.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Additional integration steps for NAO SDK\"\n}\n[/block]\nOnce you have replaced the file. Ensure it is linked to your project by selecting it in the project configuration.\n\n>>Image\n\n##Additional dependencies\n\nApart of the required MOCA SDK dependencies. You'll need to add the following additional dependencies:\n\n`libz.tbd`\n`libc++.tbd`\n`CoreMotion.framework`\n\n##Additional configuration ni your `<<AppName>>.Info.plist`\n\n<dict>\n<key>NSThirdPartyExceptionMinimumTLSVersion</key>\n<string>TLSv1.0</string>\n<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>\n<false/>\n<key>NSIncludesSubdomains</key>\n<true/>\n</dict>\n\n###Background mode.\n\n- Click in your project name > Capabilities\n- Go to _Background modes_ and select _location updates_. This mode is needed in order to detect indoor geofences when the application is not running.\n\nNOTE: This section is a summary of the additional steps required by NAO SDK according to PoleStar in the official documentation. We make an effort to maintain this docs as up to date as possible, however always take a look to the NAO official docs in order to check there hasn't been any changes since the last time we checked.\nhttps://docs.nao-cloud.com/docs/nao-sdk/ios-sdk/\n[block:api-header]\n{\n  \"title\": \"NAO API Key configuration\"\n}\n[/block]\nBefore starting to integrate the code, you will need to add a NAO API Key to the Indoor-Enabled place in your MOCA Console.\n\nNOTE: Currently there is no UI to add this key to the MOCA Place. Please send us a message to support@mocaplatform.com with your NAO API Key, the account where you want to add the Key, and the Place name or place ID\n\n##Emulator key\n\nNAO allows the usage of an \"emulator\" key, very useful during the integration step. Please create a place and a geofence around where you physically are developing the application and let us know what that place is, so we can add an emulator key that will work in the development enviroment.\n[block:api-header]\n{\n  \"title\": \"MOCA Indoor Location interface\"\n}\n[/block]\nOnce you have configured the SDK. You are now ready to use the Indoor Location API.\n\n##Creating an Indoor Location Client\n\nUse the following method to request a new client:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"-(MOCAIndoorClient *) indoorLocationClientWithDelegate:(id <MOCAIndoorDelegate> *) delegate;\\n\\n//Usage\\n\\nMOCAIndoorClient *myClient = [MOCA indoorLocationClientWithDelegate:self];\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\nYour class must implement the `MOCAIndoorDelegate`protocol in order to receive Location Updates.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@protocol MOCAIndoorLocationDelegate <NSObject>\\n\\n-(void) indoorTracker:(MOCAIndoorClient*) client didUpdateToLocation:(CLLocation *) location;\\n-(void) didFailWithError:(MOCAIndoorError) error message:(NSString*) message;\\n-(void) didReceiveWarning: (MOCAIndoorWarning) warning message:(NSString*) message;\\n-(void) didSynchronizeClient: (MOCAIndoorClient*) client;\\n\\n\\n@end\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n## Getting location updates\n\n1 - After creating the client, start it: \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n[myClient start];\\n\",\n      \"language\": \"objectivec\"\n    }\n  ]\n}\n[/block]\n\nThe Indoor Location Engine will return location data once every second, you will need to connect the map with the engine in the indoorClient::didUpdateToLocation method of your delegate.\n[block:api-header]\n{\n  \"title\": \"Messages, Warnings and errors\"\n}\n[/block]\nClient will let you know the status of the engine by calling your warning, or error or didSynchronizeClient callbacks. \n\n`didSynchronizeClient`\n Client has successfully synced data with cloud.\n`Warnings`: Non-fatal codes:  \n- `LocationTemporaryUnavailable`: Device is going off site.  \n- `SyncError` Synchronization error. No internet access or HTTP error.  \n- `NoLocationPermission` User has not granted location permission.  \n- `BleNotEnabled` Bluetooth is turned off and it is needed for indoor location.  \n- `WifiNotEnabled` Wifi is turned off and it is needed for indoor location.  \n- `RequiresCompassCalibration` Compass calibration required.  \n- `NoIndoorData`: Cloud Sync failed. If no local data is available (PDBs and app.json), engine won’t be able to start.  \n\n`Errors`: Fatal codes:  \n- `GenericError`: Something went wrong.  \n- `InvalidPlaceConfiguration`: Check the NAO configuration in the MOCA Console. Nao key is not valid.  \n- `UnsupportedOS`: You are running on an unsupported device.  \n- `NoIndoorData`: Local data not available or not valid. Could be fixed by callinx `[myClient sync]`.  \n[block:api-header]\n{\n  \"title\": \"Tie the UIViewController with the tracker life cycle\"\n}\n[/block]\nStop the client when the Map view is no longer visible to save battery. Use the method:\n\n`[myClient stop];`\n\nTeardown the client when the map view is about to be destroyed, so all its resources can be released.\n\n`[myClient close];`\n\nResume location when Map view is visible again\n\n`[myClient start];`","excerpt":"","slug":"indoor-location-api","type":"basic","title":"Indoor Location API","__v":0,"parentDoc":null,"childrenPages":[]}

Indoor Location API


Through the MOCA Indoor Location API, mobile applications are able get their current location indoors with GPS-grade accuracy. Location is provided by using and combining signals from a variety of sensors, including Bluetooth, Wi-Fi or Microelectromechanical systems (Gyroscope, Compass, and Accelerometer). MOCA SDK relies on 3rd party software to calculate the device location. MOCA SDK for iOS includes the necessary dependency into the static library. If you want to use this API, you will need to replace your `libMOCALib.a` with the following: ##Indoor Enabled MOCA SDKs for iOS: - MOCA SDK + NAO SDK v2.4.3n: [link](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/nao/moca-ios-sdk-v2.4.3n.zip) _(latest update: 2018-01-14)_ ##Changelog v2.3.3 / v2.3.3n - Allow set the location permission strategy property in the Config object. - Check if beacon setting is enabled before starting to range beacons - Added an error message when trying to create an indoor client without the NAO Dependency available. NAO is a trademark from PoleStar SA. Learn more about PoleStar solutions at [http://www.polestar.eu/](http://www.polestar.eu/) [block:callout] { "type": "danger", "body": "You will need an account with PoleStar in order to use this feature." } [/block] [block:api-header] { "title": "Additional integration steps for NAO SDK" } [/block] Once you have replaced the file. Ensure it is linked to your project by selecting it in the project configuration. >>Image ##Additional dependencies Apart of the required MOCA SDK dependencies. You'll need to add the following additional dependencies: `libz.tbd` `libc++.tbd` `CoreMotion.framework` ##Additional configuration ni your `<<AppName>>.Info.plist` <dict> <key>NSThirdPartyExceptionMinimumTLSVersion</key> <string>TLSv1.0</string> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> <key>NSIncludesSubdomains</key> <true/> </dict> ###Background mode. - Click in your project name > Capabilities - Go to _Background modes_ and select _location updates_. This mode is needed in order to detect indoor geofences when the application is not running. NOTE: This section is a summary of the additional steps required by NAO SDK according to PoleStar in the official documentation. We make an effort to maintain this docs as up to date as possible, however always take a look to the NAO official docs in order to check there hasn't been any changes since the last time we checked. https://docs.nao-cloud.com/docs/nao-sdk/ios-sdk/ [block:api-header] { "title": "NAO API Key configuration" } [/block] Before starting to integrate the code, you will need to add a NAO API Key to the Indoor-Enabled place in your MOCA Console. NOTE: Currently there is no UI to add this key to the MOCA Place. Please send us a message to support@mocaplatform.com with your NAO API Key, the account where you want to add the Key, and the Place name or place ID ##Emulator key NAO allows the usage of an "emulator" key, very useful during the integration step. Please create a place and a geofence around where you physically are developing the application and let us know what that place is, so we can add an emulator key that will work in the development enviroment. [block:api-header] { "title": "MOCA Indoor Location interface" } [/block] Once you have configured the SDK. You are now ready to use the Indoor Location API. ##Creating an Indoor Location Client Use the following method to request a new client: [block:code] { "codes": [ { "code": "-(MOCAIndoorClient *) indoorLocationClientWithDelegate:(id <MOCAIndoorDelegate> *) delegate;\n\n//Usage\n\nMOCAIndoorClient *myClient = [MOCA indoorLocationClientWithDelegate:self];", "language": "objectivec" } ] } [/block] Your class must implement the `MOCAIndoorDelegate`protocol in order to receive Location Updates. [block:code] { "codes": [ { "code": "@protocol MOCAIndoorLocationDelegate <NSObject>\n\n-(void) indoorTracker:(MOCAIndoorClient*) client didUpdateToLocation:(CLLocation *) location;\n-(void) didFailWithError:(MOCAIndoorError) error message:(NSString*) message;\n-(void) didReceiveWarning: (MOCAIndoorWarning) warning message:(NSString*) message;\n-(void) didSynchronizeClient: (MOCAIndoorClient*) client;\n\n\n@end\n", "language": "objectivec" } ] } [/block] ## Getting location updates 1 - After creating the client, start it: [block:code] { "codes": [ { "code": "\n[myClient start];\n", "language": "objectivec" } ] } [/block] The Indoor Location Engine will return location data once every second, you will need to connect the map with the engine in the indoorClient::didUpdateToLocation method of your delegate. [block:api-header] { "title": "Messages, Warnings and errors" } [/block] Client will let you know the status of the engine by calling your warning, or error or didSynchronizeClient callbacks. `didSynchronizeClient` Client has successfully synced data with cloud. `Warnings`: Non-fatal codes: - `LocationTemporaryUnavailable`: Device is going off site. - `SyncError` Synchronization error. No internet access or HTTP error. - `NoLocationPermission` User has not granted location permission. - `BleNotEnabled` Bluetooth is turned off and it is needed for indoor location. - `WifiNotEnabled` Wifi is turned off and it is needed for indoor location. - `RequiresCompassCalibration` Compass calibration required. - `NoIndoorData`: Cloud Sync failed. If no local data is available (PDBs and app.json), engine won’t be able to start. `Errors`: Fatal codes: - `GenericError`: Something went wrong. - `InvalidPlaceConfiguration`: Check the NAO configuration in the MOCA Console. Nao key is not valid. - `UnsupportedOS`: You are running on an unsupported device. - `NoIndoorData`: Local data not available or not valid. Could be fixed by callinx `[myClient sync]`. [block:api-header] { "title": "Tie the UIViewController with the tracker life cycle" } [/block] Stop the client when the Map view is no longer visible to save battery. Use the method: `[myClient stop];` Teardown the client when the map view is about to be destroyed, so all its resources can be released. `[myClient close];` Resume location when Map view is visible again `[myClient start];`
Through the MOCA Indoor Location API, mobile applications are able get their current location indoors with GPS-grade accuracy. Location is provided by using and combining signals from a variety of sensors, including Bluetooth, Wi-Fi or Microelectromechanical systems (Gyroscope, Compass, and Accelerometer). MOCA SDK relies on 3rd party software to calculate the device location. MOCA SDK for iOS includes the necessary dependency into the static library. If you want to use this API, you will need to replace your `libMOCALib.a` with the following: ##Indoor Enabled MOCA SDKs for iOS: - MOCA SDK + NAO SDK v2.4.3n: [link](https://s3-eu-west-1.amazonaws.com/files.mocaplatform.com/releases/nao/moca-ios-sdk-v2.4.3n.zip) _(latest update: 2018-01-14)_ ##Changelog v2.3.3 / v2.3.3n - Allow set the location permission strategy property in the Config object. - Check if beacon setting is enabled before starting to range beacons - Added an error message when trying to create an indoor client without the NAO Dependency available. NAO is a trademark from PoleStar SA. Learn more about PoleStar solutions at [http://www.polestar.eu/](http://www.polestar.eu/) [block:callout] { "type": "danger", "body": "You will need an account with PoleStar in order to use this feature." } [/block] [block:api-header] { "title": "Additional integration steps for NAO SDK" } [/block] Once you have replaced the file. Ensure it is linked to your project by selecting it in the project configuration. >>Image ##Additional dependencies Apart of the required MOCA SDK dependencies. You'll need to add the following additional dependencies: `libz.tbd` `libc++.tbd` `CoreMotion.framework` ##Additional configuration ni your `<<AppName>>.Info.plist` <dict> <key>NSThirdPartyExceptionMinimumTLSVersion</key> <string>TLSv1.0</string> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> <key>NSIncludesSubdomains</key> <true/> </dict> ###Background mode. - Click in your project name > Capabilities - Go to _Background modes_ and select _location updates_. This mode is needed in order to detect indoor geofences when the application is not running. NOTE: This section is a summary of the additional steps required by NAO SDK according to PoleStar in the official documentation. We make an effort to maintain this docs as up to date as possible, however always take a look to the NAO official docs in order to check there hasn't been any changes since the last time we checked. https://docs.nao-cloud.com/docs/nao-sdk/ios-sdk/ [block:api-header] { "title": "NAO API Key configuration" } [/block] Before starting to integrate the code, you will need to add a NAO API Key to the Indoor-Enabled place in your MOCA Console. NOTE: Currently there is no UI to add this key to the MOCA Place. Please send us a message to support@mocaplatform.com with your NAO API Key, the account where you want to add the Key, and the Place name or place ID ##Emulator key NAO allows the usage of an "emulator" key, very useful during the integration step. Please create a place and a geofence around where you physically are developing the application and let us know what that place is, so we can add an emulator key that will work in the development enviroment. [block:api-header] { "title": "MOCA Indoor Location interface" } [/block] Once you have configured the SDK. You are now ready to use the Indoor Location API. ##Creating an Indoor Location Client Use the following method to request a new client: [block:code] { "codes": [ { "code": "-(MOCAIndoorClient *) indoorLocationClientWithDelegate:(id <MOCAIndoorDelegate> *) delegate;\n\n//Usage\n\nMOCAIndoorClient *myClient = [MOCA indoorLocationClientWithDelegate:self];", "language": "objectivec" } ] } [/block] Your class must implement the `MOCAIndoorDelegate`protocol in order to receive Location Updates. [block:code] { "codes": [ { "code": "@protocol MOCAIndoorLocationDelegate <NSObject>\n\n-(void) indoorTracker:(MOCAIndoorClient*) client didUpdateToLocation:(CLLocation *) location;\n-(void) didFailWithError:(MOCAIndoorError) error message:(NSString*) message;\n-(void) didReceiveWarning: (MOCAIndoorWarning) warning message:(NSString*) message;\n-(void) didSynchronizeClient: (MOCAIndoorClient*) client;\n\n\n@end\n", "language": "objectivec" } ] } [/block] ## Getting location updates 1 - After creating the client, start it: [block:code] { "codes": [ { "code": "\n[myClient start];\n", "language": "objectivec" } ] } [/block] The Indoor Location Engine will return location data once every second, you will need to connect the map with the engine in the indoorClient::didUpdateToLocation method of your delegate. [block:api-header] { "title": "Messages, Warnings and errors" } [/block] Client will let you know the status of the engine by calling your warning, or error or didSynchronizeClient callbacks. `didSynchronizeClient` Client has successfully synced data with cloud. `Warnings`: Non-fatal codes: - `LocationTemporaryUnavailable`: Device is going off site. - `SyncError` Synchronization error. No internet access or HTTP error. - `NoLocationPermission` User has not granted location permission. - `BleNotEnabled` Bluetooth is turned off and it is needed for indoor location. - `WifiNotEnabled` Wifi is turned off and it is needed for indoor location. - `RequiresCompassCalibration` Compass calibration required. - `NoIndoorData`: Cloud Sync failed. If no local data is available (PDBs and app.json), engine won’t be able to start. `Errors`: Fatal codes: - `GenericError`: Something went wrong. - `InvalidPlaceConfiguration`: Check the NAO configuration in the MOCA Console. Nao key is not valid. - `UnsupportedOS`: You are running on an unsupported device. - `NoIndoorData`: Local data not available or not valid. Could be fixed by callinx `[myClient sync]`. [block:api-header] { "title": "Tie the UIViewController with the tracker life cycle" } [/block] Stop the client when the Map view is no longer visible to save battery. Use the method: `[myClient stop];` Teardown the client when the map view is about to be destroyed, so all its resources can be released. `[myClient close];` Resume location when Map view is visible again `[myClient start];`
{"_id":"59198f21eba9ac310001860b","api":{"url":"","results":{"codes":[{"code":"{}","language":"json","status":200,"name":""},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[]},"link_external":false,"next":{"pages":[],"description":""},"slug":"proximity-events-delegate","type":"basic","updates":[],"order":11,"body":"Implement MOCAProximityEventsDelegate to handle proximity events:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@interface AppDelegate : UIResponder <UIApplicationDelegate, MOCAProximityEventsDelegate>\\n\\n…\\n\\nMOCAProximityService * proxService = [MOCA proximityService];\\nif (proxService)\\n{\\n    // Notify me when beacon-related events are fired.\\n    proxService.eventsDelegate = self;\\n}\\n\\n/**\\n * Method invoked when a proximity service loaded or updated a registry of beacons\\n * from MOCA cloud.\\n *\\n * @param service proximity service\\n * @param beacons current collection of registered beacons\\n *\\n * @return YES if the custom trigger fired, or NO otherwise.\\n */\\n-(void)proximityService:(MOCAProximityService*)service\\n   didLoadedBeaconsData:(NSArray*)beacons\\n{\\n    NSLog(@\\\"Current beacon registry:\\\");\\n    for (MOCABeacon * beacon in beacons)\\n    {\\n        NSLog(@\\\"\\\\tBeacon name %@, UUID %@, Major %@, Minor %@\\\", \\u000b           beacon.name, [beacon.proximityUUID UUIDString], beacon.major, beacon.minor);\\n    }\\n}\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"…\\n\\nlet proxService: MOCAProximityService? = MOCA.proximityService()\\nif proxService != nil {\\n// Notify me when beacon-related events are fired.\\nproxService?.eventsDelegate(self)\\n}\\n\\n/**\\n* Method invoked when a proximity service loaded or updated a registry of beacons\\n* from MOCA cloud.\\n*\\n* @param service proximity service\\n* @param beacons current collection of registered beacons\\n*\\n* @return YES if the custom trigger fired, or NO otherwise.\\n*/\\n\\nfunc proximityService(_ service: MOCAProximityService, didLoadedBeaconsData beacons: [MOCABeacon]) {\\nprint(\\\"Current beacon registry:\\\")\\nfor beacon in beacons {\\nprint(\\\"\\\\tBeacon name \\\\(beacon.name), UUID \\\\(beacon.floor), Major \\\\(beacon.location), Minor \\\\(beacon.proximity)\\\")\\n}\\n}\\n\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\nThe MOCAProximityEventsDelegate exposes the following events:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@protocol MOCAProximityEventsDelegate <NSObject>\\n\\n@optional\\n\\n-(void)proximityService:(MOCAProximityService*)service didEnterRange:(MOCABeacon *)beacon withProximity:(CLProximity)proximity;\\n-(void)proximityService:(MOCAProximityService*)service didExitRange:(MOCABeacon *)beacon;\\n-(void)proximityService:(MOCAProximityService*)service didBeaconProximityChange:(MOCABeacon*)beacon\\n               fromProximity:(CLProximity)prevProximity toProximity:(CLProximity)curProximity;\\n\\n-(void)proximityService:(MOCAProximityService*)service didEnterPlace:(MOCAPlace *)place;\\n-(void)proximityService:(MOCAProximityService*)service didExitPlace:(MOCAPlace *)place;\\n\\n-(void)proximityService:(MOCAProximityService*)service didEnterZone:(MOCAZone *)zone;\\n-(void)proximityService:(MOCAProximityService*)service didExitZone:(MOCAZone *)zone;\\n\\n-(BOOL)proximityService:(MOCAProximityService*)service handleCustomTrigger:(NSString*)customAttribute;\\n\\n-(void)proximityService:(MOCAProximityService*)service didLoadedBeaconsData:(NSArray*)beacons;\\n\\n@end\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"protocol MOCAProximityEventsDelegate: NSObjectProtocol {\\nfunc proximityService(_ service: MOCAProximityService, didEnterRange beacon: MOCABeacon, with proximity: CLProximity)\\n\\nfunc proximityService(_ service: MOCAProximityService, didExitRange beacon: MOCABeacon)\\n\\nfunc proximityService(_ service: MOCAProximityService, didBeaconProximityChange beacon: MOCABeacon, from prevProximity: CLProximity, to curProximity: CLProximity)\\n\\nfunc proximityService(_ service: MOCAProximityService, didEnter place: MOCAPlace)\\n\\nfunc proximityService(_ service: MOCAProximityService, didExitPlace place: MOCAPlace)\\n\\nfunc proximityService(_ service: MOCAProximityService, didEnter zone: MOCAZone)\\n\\nfunc proximityService(_ service: MOCAProximityService, didExitZone zone: MOCAZone)\\n\\nfunc proximityService(_ service: MOCAProximityService, handleCustomTrigger customAttribute: String) -> Bool\\n\\nfunc proximityService(_ service: MOCAProximityService, didLoadedBeaconsData beacons: [Any])\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"These methods are completely optional. You don't need to implement them in order to get Proximity Experiences. \\nImplement these methods if you want to have a deeper integration with MOCA SDK. (e.g. custom information in your app views).\"\n}\n[/block]","githubsync":"","isReference":false,"link_url":"","sync_unique":"","user":"559a618bdbcfd20d00710b38","title":"Proximity Events Delegate","__v":0,"category":"59198f20eba9ac31000185e1","createdAt":"2015-07-17T14:03:28.610Z","excerpt":"","hidden":false,"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","version":"59198f1eeba9ac31000185de","childrenPages":[]}

Proximity Events Delegate


Implement MOCAProximityEventsDelegate to handle proximity events: [block:code] { "codes": [ { "code": "@interface AppDelegate : UIResponder <UIApplicationDelegate, MOCAProximityEventsDelegate>\n\n…\n\nMOCAProximityService * proxService = [MOCA proximityService];\nif (proxService)\n{\n // Notify me when beacon-related events are fired.\n proxService.eventsDelegate = self;\n}\n\n/**\n * Method invoked when a proximity service loaded or updated a registry of beacons\n * from MOCA cloud.\n *\n * @param service proximity service\n * @param beacons current collection of registered beacons\n *\n * @return YES if the custom trigger fired, or NO otherwise.\n */\n-(void)proximityService:(MOCAProximityService*)service\n didLoadedBeaconsData:(NSArray*)beacons\n{\n NSLog(@\"Current beacon registry:\");\n for (MOCABeacon * beacon in beacons)\n {\n NSLog(@\"\\tBeacon name %@, UUID %@, Major %@, Minor %@\", \u000b beacon.name, [beacon.proximityUUID UUIDString], beacon.major, beacon.minor);\n }\n}\n", "language": "objectivec" }, { "code": "…\n\nlet proxService: MOCAProximityService? = MOCA.proximityService()\nif proxService != nil {\n// Notify me when beacon-related events are fired.\nproxService?.eventsDelegate(self)\n}\n\n/**\n* Method invoked when a proximity service loaded or updated a registry of beacons\n* from MOCA cloud.\n*\n* @param service proximity service\n* @param beacons current collection of registered beacons\n*\n* @return YES if the custom trigger fired, or NO otherwise.\n*/\n\nfunc proximityService(_ service: MOCAProximityService, didLoadedBeaconsData beacons: [MOCABeacon]) {\nprint(\"Current beacon registry:\")\nfor beacon in beacons {\nprint(\"\\tBeacon name \\(beacon.name), UUID \\(beacon.floor), Major \\(beacon.location), Minor \\(beacon.proximity)\")\n}\n}\n", "language": "swift" } ] } [/block] The MOCAProximityEventsDelegate exposes the following events: [block:code] { "codes": [ { "code": "@protocol MOCAProximityEventsDelegate <NSObject>\n\n@optional\n\n-(void)proximityService:(MOCAProximityService*)service didEnterRange:(MOCABeacon *)beacon withProximity:(CLProximity)proximity;\n-(void)proximityService:(MOCAProximityService*)service didExitRange:(MOCABeacon *)beacon;\n-(void)proximityService:(MOCAProximityService*)service didBeaconProximityChange:(MOCABeacon*)beacon\n fromProximity:(CLProximity)prevProximity toProximity:(CLProximity)curProximity;\n\n-(void)proximityService:(MOCAProximityService*)service didEnterPlace:(MOCAPlace *)place;\n-(void)proximityService:(MOCAProximityService*)service didExitPlace:(MOCAPlace *)place;\n\n-(void)proximityService:(MOCAProximityService*)service didEnterZone:(MOCAZone *)zone;\n-(void)proximityService:(MOCAProximityService*)service didExitZone:(MOCAZone *)zone;\n\n-(BOOL)proximityService:(MOCAProximityService*)service handleCustomTrigger:(NSString*)customAttribute;\n\n-(void)proximityService:(MOCAProximityService*)service didLoadedBeaconsData:(NSArray*)beacons;\n\n@end\n", "language": "objectivec" }, { "code": "protocol MOCAProximityEventsDelegate: NSObjectProtocol {\nfunc proximityService(_ service: MOCAProximityService, didEnterRange beacon: MOCABeacon, with proximity: CLProximity)\n\nfunc proximityService(_ service: MOCAProximityService, didExitRange beacon: MOCABeacon)\n\nfunc proximityService(_ service: MOCAProximityService, didBeaconProximityChange beacon: MOCABeacon, from prevProximity: CLProximity, to curProximity: CLProximity)\n\nfunc proximityService(_ service: MOCAProximityService, didEnter place: MOCAPlace)\n\nfunc proximityService(_ service: MOCAProximityService, didExitPlace place: MOCAPlace)\n\nfunc proximityService(_ service: MOCAProximityService, didEnter zone: MOCAZone)\n\nfunc proximityService(_ service: MOCAProximityService, didExitZone zone: MOCAZone)\n\nfunc proximityService(_ service: MOCAProximityService, handleCustomTrigger customAttribute: String) -> Bool\n\nfunc proximityService(_ service: MOCAProximityService, didLoadedBeaconsData beacons: [Any])\n}", "language": "swift" } ] } [/block] [block:callout] { "type": "warning", "body": "These methods are completely optional. You don't need to implement them in order to get Proximity Experiences. \nImplement these methods if you want to have a deeper integration with MOCA SDK. (e.g. custom information in your app views)." } [/block]
Implement MOCAProximityEventsDelegate to handle proximity events: [block:code] { "codes": [ { "code": "@interface AppDelegate : UIResponder <UIApplicationDelegate, MOCAProximityEventsDelegate>\n\n…\n\nMOCAProximityService * proxService = [MOCA proximityService];\nif (proxService)\n{\n // Notify me when beacon-related events are fired.\n proxService.eventsDelegate = self;\n}\n\n/**\n * Method invoked when a proximity service loaded or updated a registry of beacons\n * from MOCA cloud.\n *\n * @param service proximity service\n * @param beacons current collection of registered beacons\n *\n * @return YES if the custom trigger fired, or NO otherwise.\n */\n-(void)proximityService:(MOCAProximityService*)service\n didLoadedBeaconsData:(NSArray*)beacons\n{\n NSLog(@\"Current beacon registry:\");\n for (MOCABeacon * beacon in beacons)\n {\n NSLog(@\"\\tBeacon name %@, UUID %@, Major %@, Minor %@\", \u000b beacon.name, [beacon.proximityUUID UUIDString], beacon.major, beacon.minor);\n }\n}\n", "language": "objectivec" }, { "code": "…\n\nlet proxService: MOCAProximityService? = MOCA.proximityService()\nif proxService != nil {\n// Notify me when beacon-related events are fired.\nproxService?.eventsDelegate(self)\n}\n\n/**\n* Method invoked when a proximity service loaded or updated a registry of beacons\n* from MOCA cloud.\n*\n* @param service proximity service\n* @param beacons current collection of registered beacons\n*\n* @return YES if the custom trigger fired, or NO otherwise.\n*/\n\nfunc proximityService(_ service: MOCAProximityService, didLoadedBeaconsData beacons: [MOCABeacon]) {\nprint(\"Current beacon registry:\")\nfor beacon in beacons {\nprint(\"\\tBeacon name \\(beacon.name), UUID \\(beacon.floor), Major \\(beacon.location), Minor \\(beacon.proximity)\")\n}\n}\n", "language": "swift" } ] } [/block] The MOCAProximityEventsDelegate exposes the following events: [block:code] { "codes": [ { "code": "@protocol MOCAProximityEventsDelegate <NSObject>\n\n@optional\n\n-(void)proximityService:(MOCAProximityService*)service didEnterRange:(MOCABeacon *)beacon withProximity:(CLProximity)proximity;\n-(void)proximityService:(MOCAProximityService*)service didExitRange:(MOCABeacon *)beacon;\n-(void)proximityService:(MOCAProximityService*)service didBeaconProximityChange:(MOCABeacon*)beacon\n fromProximity:(CLProximity)prevProximity toProximity:(CLProximity)curProximity;\n\n-(void)proximityService:(MOCAProximityService*)service didEnterPlace:(MOCAPlace *)place;\n-(void)proximityService:(MOCAProximityService*)service didExitPlace:(MOCAPlace *)place;\n\n-(void)proximityService:(MOCAProximityService*)service didEnterZone:(MOCAZone *)zone;\n-(void)proximityService:(MOCAProximityService*)service didExitZone:(MOCAZone *)zone;\n\n-(BOOL)proximityService:(MOCAProximityService*)service handleCustomTrigger:(NSString*)customAttribute;\n\n-(void)proximityService:(MOCAProximityService*)service didLoadedBeaconsData:(NSArray*)beacons;\n\n@end\n", "language": "objectivec" }, { "code": "protocol MOCAProximityEventsDelegate: NSObjectProtocol {\nfunc proximityService(_ service: MOCAProximityService, didEnterRange beacon: MOCABeacon, with proximity: CLProximity)\n\nfunc proximityService(_ service: MOCAProximityService, didExitRange beacon: MOCABeacon)\n\nfunc proximityService(_ service: MOCAProximityService, didBeaconProximityChange beacon: MOCABeacon, from prevProximity: CLProximity, to curProximity: CLProximity)\n\nfunc proximityService(_ service: MOCAProximityService, didEnter place: MOCAPlace)\n\nfunc proximityService(_ service: MOCAProximityService, didExitPlace place: MOCAPlace)\n\nfunc proximityService(_ service: MOCAProximityService, didEnter zone: MOCAZone)\n\nfunc proximityService(_ service: MOCAProximityService, didExitZone zone: MOCAZone)\n\nfunc proximityService(_ service: MOCAProximityService, handleCustomTrigger customAttribute: String) -> Bool\n\nfunc proximityService(_ service: MOCAProximityService, didLoadedBeaconsData beacons: [Any])\n}", "language": "swift" } ] } [/block] [block:callout] { "type": "warning", "body": "These methods are completely optional. You don't need to implement them in order to get Proximity Experiences. \nImplement these methods if you want to have a deeper integration with MOCA SDK. (e.g. custom information in your app views)." } [/block]
{"_id":"59198f21eba9ac310001860c","hidden":false,"order":12,"updates":[],"body":"You may also customize actions using MOCAProximityActionsDelegate:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@protocol MOCAProximityActionsDelegate <NSObject>\\n\\n@optional\\n\\n/**\\n * Called to determine if a specific proximity action can be executed now.\\n * @param service - proximity service instance\\n *\\n * Discussion\\n *\\n * It is typically implemented by the hosting app that wants to control\\n * when the experiences should be displayed and when not.\\n * \\n * Example\\n *\\n * An app that displays a splash screen may want to enable proximity actions\\n * to be displayed only after displaying the home screen.\\n */\\n-(BOOL)actionCanDisplayNow:(MOCAAction*)sender withSituation:(MOCAFireSituation)situation;\\n\\n/**\\n * Called when action if fired and accepted by actionCanDisplayNow() method.\\n * This method is invoked for all action types and should be used to perform generic action logic.\\n * @return YES if action execution flow should proceed, or NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender withSituation:(MOCAFireSituation)situation;\\n\\n/**\\n * Called when an alert notification should be displayed to a user.\\n * @param alertMessage a simple string to be displayed as an alert\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender displayNotificationAlert:(NSString *)alertMessage withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when a URL content should be displayed to a user.\\n * @param url a content URL to be displayed\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender openUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when a embedded HTML content should be displayed to a user.\\n * @param html a HTML content to be displayed\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender showHtmlWithString:(NSString*)html withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when a video from URL should be played to a user.\\n * @param url - video content URL\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender playVideoFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when an image from URL should be displayed to a user.\\n * @param url - image URL\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender displayImageFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when a Passbook pass card from URL should be displayed to a user.\\n * @param url - pass URL\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender displayPassFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when a user should be tagged.\\n * @param tagName name of the tag\\n * @param value value to be added\\n * @return YES if the tag should be added to user profile, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender addTag:(NSString*)tagName withValue:(NSString*)value;\\n\\n/*\\n * Called when a sound notification should be played.\\n * @param soundFilename The sound file to play or `default` for the standard notification sound.\\n * This file must be included in the application bundle or available in system bundle.\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender playNotificationSound:(NSString *)soundFilename withSituation:(MOCAFireSituation)situation;\\n\\n/*\\n * Called when the app should execute a custom action.\\n * @param customAttribute - user provided custom attribute\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\n-(BOOL)action:(MOCAAction*)sender performCustomAction:(NSString*)customAttribute withSituation:(MOCAFireSituation)situation;\\n\\n/** \\n * Called to customize the app root view that should be used to display overlay popup window.\\n * @param view - default superview to add the overlay to as a child view.\\n * @return selected view to be used as superview.\\n */\\n-(UIView*)willShowOverlayInView:(UIView*) superview;\\n\\n@end\\n\\n\",\n      \"language\": \"objectivec\"\n    },\n    {\n      \"code\": \"protocol MOCAProximityActionsDelegate: NSObjectProtocol {\\n\\n/**\\n * Called to determine if a specific proximity action can be executed now.\\n * @param service - proximity service instance\\n *\\n * Discussion\\n *\\n * It is typically implemented by the hosting app that wants to control\\n * when the experiences should be displayed and when not.\\n * \\n * Example\\n *\\n * An app that displays a splash screen may want to enable proximity actions\\n * to be displayed only after displaying the home screen.\\n */\\nfunc actionCanDisplayNow(_ sender: MOCAAction, with situation: MOCAFireSituation) -> Bool\\n\\n/**\\n * Called when action if fired and accepted by actionCanDisplayNow() method.\\n * This method is invoked for all action types and should be used to perform generic action logic.\\n * @return YES if action execution flow should proceed, or NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, with situation: MOCAFireSituation) -> Bool\\n\\n/**\\n * Called when an alert notification should be displayed to a user.\\n * @param alertMessage a simple string to be displayed as an alert\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, displayNotificationAlert alertMessage: String, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when a URL content should be displayed to a user.\\n * @param url a content URL to be displayed\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, open url: URL, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when a embedded HTML content should be displayed to a user.\\n * @param html a HTML content to be displayed\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, showHtmlWith html: String, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when a video from URL should be played to a user.\\n * @param url - video content URL\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, playVideoFrom url: URL, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when an image from URL should be displayed to a user.\\n * @param url - image URL\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, displayImageFrom url: URL, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when a Passbook pass card from URL should be displayed to a user.\\n * @param url - pass URL\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, displayPassFrom url: URL, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when a user should be tagged.\\n * @param tagName name of the tag\\n * @param value value to be added\\n * @return YES if the tag should be added to user profile, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, addTag tagName: String, withValue value: String) -> Bool\\n\\n/*\\n * Called when a sound notification should be played.\\n * @param soundFilename The sound file to play or `default` for the standard notification sound.\\n * This file must be included in the application bundle or available in system bundle.\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, playNotificationSound soundFilename: String, with situation: MOCAFireSituation) -> Bool\\n\\n/*\\n * Called when the app should execute a custom action.\\n * @param customAttribute - user provided custom attribute\\n * @return YES if the alert was shown to the user, NO otherwise.\\n */\\nfunc action(_ sender: MOCAAction, performCustomAction customAttribute: String, with situation: MOCAFireSituation) -> Bool\\n\\n/** \\n * Called to customize the app root view that should be used to display overlay popup window.\\n * @param view - default superview to add the overlay to as a child view.\\n * @return selected view to be used as superview.\\n */\\nfunc willShowOverlay(in superview: UIView) -> UIView\\n}\",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"Use these methods to **override** MOCA SDK default behavior.\"\n}\n[/block]","category":"59198f20eba9ac31000185e1","createdAt":"2015-07-17T14:08:22.327Z","isReference":false,"type":"basic","parentDoc":null,"slug":"proximity-actions-delegate","sync_unique":"","__v":0,"excerpt":"","link_url":"","next":{"description":"","pages":[]},"user":"559a618bdbcfd20d00710b38","version":"59198f1eeba9ac31000185de","api":{"params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required"},"githubsync":"","link_external":false,"project":"559a61d2dbcfd20d00710b39","title":"Proximity Actions Delegate","childrenPages":[]}

Proximity Actions Delegate


You may also customize actions using MOCAProximityActionsDelegate: [block:code] { "codes": [ { "code": "@protocol MOCAProximityActionsDelegate <NSObject>\n\n@optional\n\n/**\n * Called to determine if a specific proximity action can be executed now.\n * @param service - proximity service instance\n *\n * Discussion\n *\n * It is typically implemented by the hosting app that wants to control\n * when the experiences should be displayed and when not.\n * \n * Example\n *\n * An app that displays a splash screen may want to enable proximity actions\n * to be displayed only after displaying the home screen.\n */\n-(BOOL)actionCanDisplayNow:(MOCAAction*)sender withSituation:(MOCAFireSituation)situation;\n\n/**\n * Called when action if fired and accepted by actionCanDisplayNow() method.\n * This method is invoked for all action types and should be used to perform generic action logic.\n * @return YES if action execution flow should proceed, or NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender withSituation:(MOCAFireSituation)situation;\n\n/**\n * Called when an alert notification should be displayed to a user.\n * @param alertMessage a simple string to be displayed as an alert\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender displayNotificationAlert:(NSString *)alertMessage withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a URL content should be displayed to a user.\n * @param url a content URL to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender openUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a embedded HTML content should be displayed to a user.\n * @param html a HTML content to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender showHtmlWithString:(NSString*)html withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a video from URL should be played to a user.\n * @param url - video content URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender playVideoFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when an image from URL should be displayed to a user.\n * @param url - image URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender displayImageFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a Passbook pass card from URL should be displayed to a user.\n * @param url - pass URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender displayPassFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a user should be tagged.\n * @param tagName name of the tag\n * @param value value to be added\n * @return YES if the tag should be added to user profile, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender addTag:(NSString*)tagName withValue:(NSString*)value;\n\n/*\n * Called when a sound notification should be played.\n * @param soundFilename The sound file to play or `default` for the standard notification sound.\n * This file must be included in the application bundle or available in system bundle.\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender playNotificationSound:(NSString *)soundFilename withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when the app should execute a custom action.\n * @param customAttribute - user provided custom attribute\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender performCustomAction:(NSString*)customAttribute withSituation:(MOCAFireSituation)situation;\n\n/** \n * Called to customize the app root view that should be used to display overlay popup window.\n * @param view - default superview to add the overlay to as a child view.\n * @return selected view to be used as superview.\n */\n-(UIView*)willShowOverlayInView:(UIView*) superview;\n\n@end\n\n", "language": "objectivec" }, { "code": "protocol MOCAProximityActionsDelegate: NSObjectProtocol {\n\n/**\n * Called to determine if a specific proximity action can be executed now.\n * @param service - proximity service instance\n *\n * Discussion\n *\n * It is typically implemented by the hosting app that wants to control\n * when the experiences should be displayed and when not.\n * \n * Example\n *\n * An app that displays a splash screen may want to enable proximity actions\n * to be displayed only after displaying the home screen.\n */\nfunc actionCanDisplayNow(_ sender: MOCAAction, with situation: MOCAFireSituation) -> Bool\n\n/**\n * Called when action if fired and accepted by actionCanDisplayNow() method.\n * This method is invoked for all action types and should be used to perform generic action logic.\n * @return YES if action execution flow should proceed, or NO otherwise.\n */\nfunc action(_ sender: MOCAAction, with situation: MOCAFireSituation) -> Bool\n\n/**\n * Called when an alert notification should be displayed to a user.\n * @param alertMessage a simple string to be displayed as an alert\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, displayNotificationAlert alertMessage: String, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a URL content should be displayed to a user.\n * @param url a content URL to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, open url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a embedded HTML content should be displayed to a user.\n * @param html a HTML content to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, showHtmlWith html: String, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a video from URL should be played to a user.\n * @param url - video content URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, playVideoFrom url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when an image from URL should be displayed to a user.\n * @param url - image URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, displayImageFrom url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a Passbook pass card from URL should be displayed to a user.\n * @param url - pass URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, displayPassFrom url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a user should be tagged.\n * @param tagName name of the tag\n * @param value value to be added\n * @return YES if the tag should be added to user profile, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, addTag tagName: String, withValue value: String) -> Bool\n\n/*\n * Called when a sound notification should be played.\n * @param soundFilename The sound file to play or `default` for the standard notification sound.\n * This file must be included in the application bundle or available in system bundle.\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, playNotificationSound soundFilename: String, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when the app should execute a custom action.\n * @param customAttribute - user provided custom attribute\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, performCustomAction customAttribute: String, with situation: MOCAFireSituation) -> Bool\n\n/** \n * Called to customize the app root view that should be used to display overlay popup window.\n * @param view - default superview to add the overlay to as a child view.\n * @return selected view to be used as superview.\n */\nfunc willShowOverlay(in superview: UIView) -> UIView\n}", "language": "swift" } ] } [/block] [block:callout] { "type": "warning", "body": "Use these methods to **override** MOCA SDK default behavior." } [/block]
You may also customize actions using MOCAProximityActionsDelegate: [block:code] { "codes": [ { "code": "@protocol MOCAProximityActionsDelegate <NSObject>\n\n@optional\n\n/**\n * Called to determine if a specific proximity action can be executed now.\n * @param service - proximity service instance\n *\n * Discussion\n *\n * It is typically implemented by the hosting app that wants to control\n * when the experiences should be displayed and when not.\n * \n * Example\n *\n * An app that displays a splash screen may want to enable proximity actions\n * to be displayed only after displaying the home screen.\n */\n-(BOOL)actionCanDisplayNow:(MOCAAction*)sender withSituation:(MOCAFireSituation)situation;\n\n/**\n * Called when action if fired and accepted by actionCanDisplayNow() method.\n * This method is invoked for all action types and should be used to perform generic action logic.\n * @return YES if action execution flow should proceed, or NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender withSituation:(MOCAFireSituation)situation;\n\n/**\n * Called when an alert notification should be displayed to a user.\n * @param alertMessage a simple string to be displayed as an alert\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender displayNotificationAlert:(NSString *)alertMessage withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a URL content should be displayed to a user.\n * @param url a content URL to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender openUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a embedded HTML content should be displayed to a user.\n * @param html a HTML content to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender showHtmlWithString:(NSString*)html withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a video from URL should be played to a user.\n * @param url - video content URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender playVideoFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when an image from URL should be displayed to a user.\n * @param url - image URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender displayImageFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a Passbook pass card from URL should be displayed to a user.\n * @param url - pass URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender displayPassFromUrl:(NSURL*)url withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when a user should be tagged.\n * @param tagName name of the tag\n * @param value value to be added\n * @return YES if the tag should be added to user profile, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender addTag:(NSString*)tagName withValue:(NSString*)value;\n\n/*\n * Called when a sound notification should be played.\n * @param soundFilename The sound file to play or `default` for the standard notification sound.\n * This file must be included in the application bundle or available in system bundle.\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender playNotificationSound:(NSString *)soundFilename withSituation:(MOCAFireSituation)situation;\n\n/*\n * Called when the app should execute a custom action.\n * @param customAttribute - user provided custom attribute\n * @return YES if the alert was shown to the user, NO otherwise.\n */\n-(BOOL)action:(MOCAAction*)sender performCustomAction:(NSString*)customAttribute withSituation:(MOCAFireSituation)situation;\n\n/** \n * Called to customize the app root view that should be used to display overlay popup window.\n * @param view - default superview to add the overlay to as a child view.\n * @return selected view to be used as superview.\n */\n-(UIView*)willShowOverlayInView:(UIView*) superview;\n\n@end\n\n", "language": "objectivec" }, { "code": "protocol MOCAProximityActionsDelegate: NSObjectProtocol {\n\n/**\n * Called to determine if a specific proximity action can be executed now.\n * @param service - proximity service instance\n *\n * Discussion\n *\n * It is typically implemented by the hosting app that wants to control\n * when the experiences should be displayed and when not.\n * \n * Example\n *\n * An app that displays a splash screen may want to enable proximity actions\n * to be displayed only after displaying the home screen.\n */\nfunc actionCanDisplayNow(_ sender: MOCAAction, with situation: MOCAFireSituation) -> Bool\n\n/**\n * Called when action if fired and accepted by actionCanDisplayNow() method.\n * This method is invoked for all action types and should be used to perform generic action logic.\n * @return YES if action execution flow should proceed, or NO otherwise.\n */\nfunc action(_ sender: MOCAAction, with situation: MOCAFireSituation) -> Bool\n\n/**\n * Called when an alert notification should be displayed to a user.\n * @param alertMessage a simple string to be displayed as an alert\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, displayNotificationAlert alertMessage: String, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a URL content should be displayed to a user.\n * @param url a content URL to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, open url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a embedded HTML content should be displayed to a user.\n * @param html a HTML content to be displayed\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, showHtmlWith html: String, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a video from URL should be played to a user.\n * @param url - video content URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, playVideoFrom url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when an image from URL should be displayed to a user.\n * @param url - image URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, displayImageFrom url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a Passbook pass card from URL should be displayed to a user.\n * @param url - pass URL\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, displayPassFrom url: URL, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when a user should be tagged.\n * @param tagName name of the tag\n * @param value value to be added\n * @return YES if the tag should be added to user profile, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, addTag tagName: String, withValue value: String) -> Bool\n\n/*\n * Called when a sound notification should be played.\n * @param soundFilename The sound file to play or `default` for the standard notification sound.\n * This file must be included in the application bundle or available in system bundle.\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, playNotificationSound soundFilename: String, with situation: MOCAFireSituation) -> Bool\n\n/*\n * Called when the app should execute a custom action.\n * @param customAttribute - user provided custom attribute\n * @return YES if the alert was shown to the user, NO otherwise.\n */\nfunc action(_ sender: MOCAAction, performCustomAction customAttribute: String, with situation: MOCAFireSituation) -> Bool\n\n/** \n * Called to customize the app root view that should be used to display overlay popup window.\n * @param view - default superview to add the overlay to as a child view.\n * @return selected view to be used as superview.\n */\nfunc willShowOverlay(in superview: UIView) -> UIView\n}", "language": "swift" } ] } [/block] [block:callout] { "type": "warning", "body": "Use these methods to **override** MOCA SDK default behavior." } [/block]
{"_id":"59198f21eba9ac310001860d","createdAt":"2015-07-17T14:24:43.591Z","link_url":"","sync_unique":"","version":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e1","body":"Location service authorization\n- By default, MOCA tracks user location and proximity interactions\n- The geo-location is tracked with 100-meter precision. \n- This is performed by means of iOS CLLocationManager\n- The user must allow the location tracking for the app (iOS 8 UseAlways mode).\n- The geo-location minimizes battery usage by employing SignificantLocationChange tracking\n- When the permission is not granted, MOCA does not track user location.\n\nHow event tracking works\n- MOCA SDK uses SQLite database stored in a local file on your phone to store all locally tracked events.\n- Periodically, when your device is connected to Internet (via Edge, 3G, LTE or WiFi), \u000bthe SDK incrementally transfers the packs of events to the cloud.\n- The local database is freed only when the transfer is successful (Store-And-Forward)\n- By default, the event transfer is performed every 15 minutes, but this may change depending on existing network conditions.\n\nBackground modes \n- MOCA SDK requires you to declare Background Modes for your app.\n- Open Capabilities tab in your App project build settings and configure the following options. The minimal configuration is as follows:\n\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/726950b-background-modes-minimal.png\",\n        \"background-modes-minimal.png\",\n        448,\n        265,\n        \"#2c4980\"\n      ]\n    }\n  ]\n}\n[/block]\n- The `Background Fetch` option is required to periodically fetch the proximity campaign data from the cloud.\n- The `Uses Bluetooth LE accessories` is used by MOCA in order to be informed about Bluetooth status in the background.\n\nOffline behavior\n- MOCA SDK downloads proximity campaigns data from the cloud asynchronously using \u000b*background fetch* mechanism. \n- The frequency is controlled by iOS and depends on the app usage pattern.\n- The downloaded data is persisted locally and on servers as a cache.\n- If the connection to Internet is not available, the cached data is used to run the campaigns.\n- This enables you to offer proximity experiences even if the Internet connection is saturated or not available.","githubsync":"","isReference":false,"slug":"design-considerations","title":"Design considerations","user":"559a618bdbcfd20d00710b38","__v":0,"hidden":false,"updates":[],"excerpt":"","link_external":false,"next":{"pages":[],"description":""},"order":13,"parentDoc":null,"project":"559a61d2dbcfd20d00710b39","type":"basic","api":{"results":{"codes":[{"code":"{}","language":"json","status":200,"name":""},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"childrenPages":[]}

Design considerations


Location service authorization - By default, MOCA tracks user location and proximity interactions - The geo-location is tracked with 100-meter precision. - This is performed by means of iOS CLLocationManager - The user must allow the location tracking for the app (iOS 8 UseAlways mode). - The geo-location minimizes battery usage by employing SignificantLocationChange tracking - When the permission is not granted, MOCA does not track user location. How event tracking works - MOCA SDK uses SQLite database stored in a local file on your phone to store all locally tracked events. - Periodically, when your device is connected to Internet (via Edge, 3G, LTE or WiFi), the SDK incrementally transfers the packs of events to the cloud. - The local database is freed only when the transfer is successful (Store-And-Forward) - By default, the event transfer is performed every 15 minutes, but this may change depending on existing network conditions. Background modes - MOCA SDK requires you to declare Background Modes for your app. - Open Capabilities tab in your App project build settings and configure the following options. The minimal configuration is as follows: [block:image] { "images": [ { "image": [ "https://files.readme.io/726950b-background-modes-minimal.png", "background-modes-minimal.png", 448, 265, "#2c4980" ] } ] } [/block] - The `Background Fetch` option is required to periodically fetch the proximity campaign data from the cloud. - The `Uses Bluetooth LE accessories` is used by MOCA in order to be informed about Bluetooth status in the background. Offline behavior - MOCA SDK downloads proximity campaigns data from the cloud asynchronously using *background fetch* mechanism. - The frequency is controlled by iOS and depends on the app usage pattern. - The downloaded data is persisted locally and on servers as a cache. - If the connection to Internet is not available, the cached data is used to run the campaigns. - This enables you to offer proximity experiences even if the Internet connection is saturated or not available.
Location service authorization - By default, MOCA tracks user location and proximity interactions - The geo-location is tracked with 100-meter precision. - This is performed by means of iOS CLLocationManager - The user must allow the location tracking for the app (iOS 8 UseAlways mode). - The geo-location minimizes battery usage by employing SignificantLocationChange tracking - When the permission is not granted, MOCA does not track user location. How event tracking works - MOCA SDK uses SQLite database stored in a local file on your phone to store all locally tracked events. - Periodically, when your device is connected to Internet (via Edge, 3G, LTE or WiFi), the SDK incrementally transfers the packs of events to the cloud. - The local database is freed only when the transfer is successful (Store-And-Forward) - By default, the event transfer is performed every 15 minutes, but this may change depending on existing network conditions. Background modes - MOCA SDK requires you to declare Background Modes for your app. - Open Capabilities tab in your App project build settings and configure the following options. The minimal configuration is as follows: [block:image] { "images": [ { "image": [ "https://files.readme.io/726950b-background-modes-minimal.png", "background-modes-minimal.png", 448, 265, "#2c4980" ] } ] } [/block] - The `Background Fetch` option is required to periodically fetch the proximity campaign data from the cloud. - The `Uses Bluetooth LE accessories` is used by MOCA in order to be informed about Bluetooth status in the background. Offline behavior - MOCA SDK downloads proximity campaigns data from the cloud asynchronously using *background fetch* mechanism. - The frequency is controlled by iOS and depends on the app usage pattern. - The downloaded data is persisted locally and on servers as a cache. - If the connection to Internet is not available, the cached data is used to run the campaigns. - This enables you to offer proximity experiences even if the Internet connection is saturated or not available.
{"_id":"59198f26eba9ac3100018663","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]\nYou'll need:\n\n- Android Studio IDE.\n- A real Android device is recommended. Otherwise you won't be able to discover bluetooth beacons.\n- Please check the Android OS [compatibility chart](doc:moca-android-sdk-compatibility-chart).\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Gradle\"\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    compile 'com.mocaplatform:moca-android-sdk:2.6.+'\\n}\",\n      \"language\": \"groovy\",\n      \"name\": \"build.gradle\"\n    }\n  ]\n}\n[/block]\nYou can also manually download the AAR from [bintray](https://bintray.com/mocaplatform/maven/moca-android)\n\nREMINDER: The build.gradle has to be the one in your app folder, not the main one in your project.\n[block:api-header]\n{\n  \"title\": \"Migration guide from v1.x to v2.x\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"body\": \"The below information is only needed if you are migrating from MOCA SDK 1.x to 2.x\"\n}\n[/block]\n##AndroidManifest.xml\n\nReceivers are now all inside MOCA SDK `AndroidManifest.xml` file. \nSo **it is safe to delete** all the declarated MOCA-related receivers from your App's `AndroidManifest.xml` file.  \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<!-- REQUIRED by MOCA to handle clicked notifications -->\\n\\t\\t<receiver android:name=\\\"com.innoquant.moca.push.MOCAPushReceiver\\\"\\n  \\t          android:exported=\\\"true\\\"\\n    \\t        android:permission=\\\"com.google.android.c2dm.permission.SEND\\\" >\\n\\t \\t\\t<intent-filter>\\n  \\t  \\t<action android:name=\\\"com.innoquant.moca.push.ACTION_PUSH_RECEIVE\\\" />\\n    \\t  <action android:name=\\\"com.innoquant.moca.push.ACTION_PUSH_DISMISSED\\\" />\\n\\t\\t\\t</intent-filter>\\n\\t\\t</receiver>\\n  \\n\\n    <!-- REQUIRED by MOCA to handle push notifications -->\\n    <receiver android:name=\\\"com.innoquant.moca.push.GcmPushReceiver\\\"\\n              android:permission=\\\"com.google.android.c2dm.permission.SEND\\\">\\n        <intent-filter>\\n            <action android:name=\\\"com.google.android.c2dm.intent.RECEIVE\\\" />\\n            <action android:name=\\\"com.google.android.c2dm.intent.REGISTRATION\\\" />\\n            <category android:name=\\\"YOUR-APP-PACKAGE-NAME\\\" />\\n        </intent-filter>\\n    </receiver>\\n  \\n\\t\\t<!-- MOCA GcmTokenListener listens to token registrations/updates -->\\n    <service android:name=\\\"com.innoquant.moca.push.GcmTokenListener\\\"\\n   \\t\\t\\t\\t\\tandroid:exported=\\\"false\\\">\\n\\t\\t\\t<intent-filter>\\n\\t\\t\\t\\t<action android:name=\\\"com.google.android.gms.iid.InstanceID\\\"/>\\n\\t\\t\\t</intent-filter>\\n\\t\\t</service>\",\n      \"language\": \"xml\"\n    }\n  ]\n}\n[/block]\nNext: [Configuration](doc:moca-android-sdk-configuration)","excerpt":"","user":"55a575ebaaf9cf1900114d73","createdAt":"2015-07-14T22:48:39.299Z","githubsync":"","isReference":false,"link_url":"","sync_unique":"","title":"Installation","version":"59198f1eeba9ac31000185de","api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required"},"category":"59198f20eba9ac31000185e2","hidden":false,"order":0,"type":"basic","__v":0,"childrenPages":[]}

Installation


[block:api-header] { "type": "basic", "title": "Requirements" } [/block] You'll need: - Android Studio IDE. - A real Android device is recommended. Otherwise you won't be able to discover bluetooth beacons. - Please check the Android OS [compatibility chart](doc:moca-android-sdk-compatibility-chart). [block:api-header] { "type": "basic", "title": "Gradle" } [/block] [block:code] { "codes": [ { "code": "repositories {\n maven { url 'https://dl.bintray.com/mocaplatform/maven' }\n}\n\nandroid {\n . . .\n}\n\ndependencies {\n . . .\n compile 'com.mocaplatform:moca-android-sdk:2.6.+'\n}", "language": "groovy", "name": "build.gradle" } ] } [/block] You can also manually download the AAR from [bintray](https://bintray.com/mocaplatform/maven/moca-android) REMINDER: The build.gradle has to be the one in your app folder, not the main one in your project. [block:api-header] { "title": "Migration guide from v1.x to v2.x" } [/block] [block:callout] { "type": "danger", "body": "The below information is only needed if you are migrating from MOCA SDK 1.x to 2.x" } [/block] ##AndroidManifest.xml Receivers are now all inside MOCA SDK `AndroidManifest.xml` file. So **it is safe to delete** all the declarated MOCA-related receivers from your App's `AndroidManifest.xml` file. [block:code] { "codes": [ { "code": "<!-- REQUIRED by MOCA to handle clicked notifications -->\n\t\t<receiver android:name=\"com.innoquant.moca.push.MOCAPushReceiver\"\n \t android:exported=\"true\"\n \t android:permission=\"com.google.android.c2dm.permission.SEND\" >\n\t \t\t<intent-filter>\n \t \t<action android:name=\"com.innoquant.moca.push.ACTION_PUSH_RECEIVE\" />\n \t <action android:name=\"com.innoquant.moca.push.ACTION_PUSH_DISMISSED\" />\n\t\t\t</intent-filter>\n\t\t</receiver>\n \n\n <!-- REQUIRED by MOCA to handle push notifications -->\n <receiver android:name=\"com.innoquant.moca.push.GcmPushReceiver\"\n android:permission=\"com.google.android.c2dm.permission.SEND\">\n <intent-filter>\n <action android:name=\"com.google.android.c2dm.intent.RECEIVE\" />\n <action android:name=\"com.google.android.c2dm.intent.REGISTRATION\" />\n <category android:name=\"YOUR-APP-PACKAGE-NAME\" />\n </intent-filter>\n </receiver>\n \n\t\t<!-- MOCA GcmTokenListener listens to token registrations/updates -->\n <service android:name=\"com.innoquant.moca.push.GcmTokenListener\"\n \t\t\t\t\tandroid:exported=\"false\">\n\t\t\t<intent-filter>\n\t\t\t\t<action android:name=\"com.google.android.gms.iid.InstanceID\"/>\n\t\t\t</intent-filter>\n\t\t</service>", "language": "xml" } ] } [/block] Next: [Configuration](doc:moca-android-sdk-configuration)
[block:api-header] { "type": "basic", "title": "Requirements" } [/block] You'll need: - Android Studio IDE. - A real Android device is recommended. Otherwise you won't be able to discover bluetooth beacons. - Please check the Android OS [compatibility chart](doc:moca-android-sdk-compatibility-chart). [block:api-header] { "type": "basic", "title": "Gradle" } [/block] [block:code] { "codes": [ { "code": "repositories {\n maven { url 'https://dl.bintray.com/mocaplatform/maven' }\n}\n\nandroid {\n . . .\n}\n\ndependencies {\n . . .\n compile 'com.mocaplatform:moca-android-sdk:2.6.+'\n}", "language": "groovy", "name": "build.gradle" } ] } [/block] You can also manually download the AAR from [bintray](https://bintray.com/mocaplatform/maven/moca-android) REMINDER: The build.gradle has to be the one in your app folder, not the main one in your project. [block:api-header] { "title": "Migration guide from v1.x to v2.x" } [/block] [block:callout] { "type": "danger", "body": "The below information is only needed if you are migrating from MOCA SDK 1.x to 2.x" } [/block] ##AndroidManifest.xml Receivers are now all inside MOCA SDK `AndroidManifest.xml` file. So **it is safe to delete** all the declarated MOCA-related receivers from your App's `AndroidManifest.xml` file. [block:code] { "codes": [ { "code": "<!-- REQUIRED by MOCA to handle clicked notifications -->\n\t\t<receiver android:name=\"com.innoquant.moca.push.MOCAPushReceiver\"\n \t android:exported=\"true\"\n \t android:permission=\"com.google.android.c2dm.permission.SEND\" >\n\t \t\t<intent-filter>\n \t \t<action android:name=\"com.innoquant.moca.push.ACTION_PUSH_RECEIVE\" />\n \t <action android:name=\"com.innoquant.moca.push.ACTION_PUSH_DISMISSED\" />\n\t\t\t</intent-filter>\n\t\t</receiver>\n \n\n <!-- REQUIRED by MOCA to handle push notifications -->\n <receiver android:name=\"com.innoquant.moca.push.GcmPushReceiver\"\n android:permission=\"com.google.android.c2dm.permission.SEND\">\n <intent-filter>\n <action android:name=\"com.google.android.c2dm.intent.RECEIVE\" />\n <action android:name=\"com.google.android.c2dm.intent.REGISTRATION\" />\n <category android:name=\"YOUR-APP-PACKAGE-NAME\" />\n </intent-filter>\n </receiver>\n \n\t\t<!-- MOCA GcmTokenListener listens to token registrations/updates -->\n <service android:name=\"com.innoquant.moca.push.GcmTokenListener\"\n \t\t\t\t\tandroid:exported=\"false\">\n\t\t\t<intent-filter>\n\t\t\t\t<action android:name=\"com.google.android.gms.iid.InstanceID\"/>\n\t\t\t</intent-filter>\n\t\t</service>", "language": "xml" } ] } [/block] Next: [Configuration](doc:moca-android-sdk-configuration)
{"_id":"59198f26eba9ac3100018664","link_external":false,"next":{"description":"","pages":[]},"order":1,"project":"559a61d2dbcfd20d00710b39","hidden":false,"excerpt":"","version":"59198f1eeba9ac31000185de","__v":0,"link_url":"","slug":"moca-android-sdk-configuration","category":"59198f20eba9ac31000185e2","body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Installing Google Play Services.\"\n}\n[/block]\nMOCA SDK requires Google Play Services 8.3.0+ as you've seen in the dependencies list above.\nIf your project is not using Google Play Services, please ensure the libraries are installed in your Android Studio before continuing.\nYou can see how to install Google Play Services by visiting this [Google guide](https://developer.android.com/studio/intro/update.html).\n\nThe two mandatory [Google Play Services](https://developers.google.com/android/guides/setup) required are:\n* com.google.android.gms:play-services-location:15.0.1\n* com.google.android.gms:play-services-gcm:15.0.1\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Grab your AppKey and AppSecret\"\n}\n[/block]\n1 - Go to 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\": \"Option A: Configuration through 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#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\\n# Custom settings\\n# Save custom settings by adding \\\"custom.\\\" prefix\\n# example custom.myCustomSetting = 1000\\ncustom.myCustomSetting = 1000\\n# Legacy notation\\nmoca.CUSTOM_PUSH_ICON = @drawable/ic_moca_logo\\n# moca.CUSTOM_NAOMICRO_APP_KEY = xxxxxx\\n# moca.CUSTOM_NAOMICRO_ENABLED = false\\n\",\n      \"language\": \"ruby\",\n      \"name\": \"MOCA.properties\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Option B: Configuration through `AndroidManifest.xml` file\"\n}\n[/block]\n- SDK Settings: you don't need to use this keys if you have used a `MOCA.properties` file.\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"Remember to paste the `moca.APP_KEY` and `moca.APP_SECRET` with the ones of your App. Otherwise the SDK won't be able to connect to MOCA Cloud.\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<application\\n             ...>\\n      <!-- MOCA SDK configuration -->\\n    <meta-data android:name=\\\"moca.APP_KEY\\\"\\n               android:value=\\\"YOUR-MOCA-APP-KEY\\\"/>\\n    <meta-data android:name=\\\"moca.APP_SECRET\\\"\\n               android:value=\\\"YOUR-MOCA-APP-SECRET\\\"/>\\n    <meta-data android:name=\\\"moca.LOG_LEVEL\\\"\\n               android:value=\\\"debug\\\"/>\\n    <meta-data android:name=\\\"moca.AUTOMATIC_PUSH_SETUP_ENABLED\\\"\\n               android:value=\\\"true\\\"/>\\n    <meta-data android:name=\\\"moca.PROXIMITY_SERVICE_ENABLED\\\"\\n               android:value=\\\"true\\\" />\\n    <meta-data android:name=\\\"moca.GEOLOCATION_SERVICE_ENABLED\\\"\\n               android:value=\\\"true\\\" />\\n    <meta-data android:name=\\\"moca.BACKGROUND_LOCATION_ENABLED\\\"\\n               android:value=\\\"true\\\" />\\n    <meta-data android:name=\\\"moca.DATA_FETCH_INTERVAL_MS\\\"\\n               android:value=\\\"auto\\\" />\\n    <meta-data android:name=\\\"moca.EVENT_UPLOAD_INTERVAL_MS\\\"\\n               android:value=\\\"auto\\\" />\\n  \\t<meta-data android:name=\\\"moca.MOCA_DRIVER_ENABLED\\\"\\n               android:value=\\\"true\\\" />\\n    <!--Optional: Include it for remote push notifications-->\\n    <!--Be careful with the space before the number-->\\n    <meta-data android:name=\\\"moca.GCM_SENDER\\\"\\n               android:value=\\\"\\\\ YOUR_GCM_SENDER_ID\\\" />\\n</application>\",\n      \"language\": \"xml\"\n    }\n  ]\n}\n[/block]\n- Be sure to replace `moca.APP_KEY` and `moca.APP_SECRET` values with the real values for your app which you found in the MOCA console. \n\nChange any setting that you need for your app:\n\n- `moca.PROXIMITY_SERVICE_ENABLED`, will enable or disable Bluetooth Beacon detection & geofence detection.\n- `moca.GEOLOCATION_SERVICE_ENABLED` – enables/disabled tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi.\n - 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 - NO – user location will not be tracked at all (either foreground nor background). Bluetooth beacons and geofences will still be detected if this flag is set to NO. \n- `moca.BACKGROUND_LOCATION_ENABLED` – enables/disables location tracking when the app is in background or suspended mode.\n - This flag has no effect if GEOLOCATION_SERVICE_ENABLED is set to NO.\n - By default background location tracking is enabled.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Android Marshmallow (6.0) permissions\"\n}\n[/block]\nRequest the `ACCESS_FINE_LOCATION` permission at Run Time, an example of how to do it is [available here.](doc:android-60-permissions).\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Needed for bluetooth scanning, Wi-Fi Scanning and Location updates\",\n  \"body\": \"Starting from Android M (6.0+), bluetooth beacons, Wi-Fi Networks, Geofences and location updates are not available if the user does not grant this permission. Please make sure you explain to the user why you need the permission before requesting it, this way you will significantly increase your location-aware audience.\"\n}\n[/block]\nMOCA SDK requires other permissions that are automatically declared in the App's `AndroidManifest.xml` at compile time. Learn more about the declared permissions [here](http://developer.mocaplatform.com/v2/page/android-included-permissions).\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\": \"import com.innoquant.moca.MOCA;\\nimport com.innoquant.moca.MOCAInstance;\\n\\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 proximity events when the `Activity` is not running (App not in foreground, for instance).\"\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","childrenPages":[]}

Configuration


[block:api-header] { "type": "basic", "title": "Installing Google Play Services." } [/block] MOCA SDK requires Google Play Services 8.3.0+ as you've seen in the dependencies list above. If your project is not using Google Play Services, please ensure the libraries are installed in your Android Studio before continuing. You can see how to install Google Play Services by visiting this [Google guide](https://developer.android.com/studio/intro/update.html). The two mandatory [Google Play Services](https://developers.google.com/android/guides/setup) required are: * com.google.android.gms:play-services-location:15.0.1 * com.google.android.gms:play-services-gcm:15.0.1 [block:api-header] { "type": "basic", "title": "Grab your AppKey and AppSecret" } [/block] 1 - Go to 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": "Option A: Configuration through 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#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\n# Custom settings\n# Save custom settings by adding \"custom.\" prefix\n# example custom.myCustomSetting = 1000\ncustom.myCustomSetting = 1000\n# Legacy notation\nmoca.CUSTOM_PUSH_ICON = @drawable/ic_moca_logo\n# moca.CUSTOM_NAOMICRO_APP_KEY = xxxxxx\n# moca.CUSTOM_NAOMICRO_ENABLED = false\n", "language": "ruby", "name": "MOCA.properties" } ] } [/block] [block:api-header] { "type": "basic", "title": "Option B: Configuration through `AndroidManifest.xml` file" } [/block] - SDK Settings: you don't need to use this keys if you have used a `MOCA.properties` file. [block:callout] { "type": "warning", "body": "Remember to paste the `moca.APP_KEY` and `moca.APP_SECRET` with the ones of your App. Otherwise the SDK won't be able to connect to MOCA Cloud." } [/block] [block:code] { "codes": [ { "code": "<application\n ...>\n <!-- MOCA SDK configuration -->\n <meta-data android:name=\"moca.APP_KEY\"\n android:value=\"YOUR-MOCA-APP-KEY\"/>\n <meta-data android:name=\"moca.APP_SECRET\"\n android:value=\"YOUR-MOCA-APP-SECRET\"/>\n <meta-data android:name=\"moca.LOG_LEVEL\"\n android:value=\"debug\"/>\n <meta-data android:name=\"moca.AUTOMATIC_PUSH_SETUP_ENABLED\"\n android:value=\"true\"/>\n <meta-data android:name=\"moca.PROXIMITY_SERVICE_ENABLED\"\n android:value=\"true\" />\n <meta-data android:name=\"moca.GEOLOCATION_SERVICE_ENABLED\"\n android:value=\"true\" />\n <meta-data android:name=\"moca.BACKGROUND_LOCATION_ENABLED\"\n android:value=\"true\" />\n <meta-data android:name=\"moca.DATA_FETCH_INTERVAL_MS\"\n android:value=\"auto\" />\n <meta-data android:name=\"moca.EVENT_UPLOAD_INTERVAL_MS\"\n android:value=\"auto\" />\n \t<meta-data android:name=\"moca.MOCA_DRIVER_ENABLED\"\n android:value=\"true\" />\n <!--Optional: Include it for remote push notifications-->\n <!--Be careful with the space before the number-->\n <meta-data android:name=\"moca.GCM_SENDER\"\n android:value=\"\\ YOUR_GCM_SENDER_ID\" />\n</application>", "language": "xml" } ] } [/block] - Be sure to replace `moca.APP_KEY` and `moca.APP_SECRET` values with the real values for your app which you found in the MOCA console. Change any setting that you need for your app: - `moca.PROXIMITY_SERVICE_ENABLED`, will enable or disable Bluetooth Beacon detection & geofence detection. - `moca.GEOLOCATION_SERVICE_ENABLED` – enables/disabled tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi. - 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. - NO – user location will not be tracked at all (either foreground nor background). Bluetooth beacons and geofences will still be detected if this flag is set to NO. - `moca.BACKGROUND_LOCATION_ENABLED` – enables/disables location tracking when the app is in background or suspended mode. - This flag has no effect if GEOLOCATION_SERVICE_ENABLED is set to NO. - By default background location tracking is enabled. [block:api-header] { "type": "basic", "title": "Android Marshmallow (6.0) permissions" } [/block] Request the `ACCESS_FINE_LOCATION` permission at Run Time, an example of how to do it is [available here.](doc:android-60-permissions). [block:callout] { "type": "danger", "title": "Needed for bluetooth scanning, Wi-Fi Scanning and Location updates", "body": "Starting from Android M (6.0+), bluetooth beacons, Wi-Fi Networks, Geofences and location updates are not available if the user does not grant this permission. Please make sure you explain to the user why you need the permission before requesting it, this way you will significantly increase your location-aware audience." } [/block] MOCA SDK requires other permissions that are automatically declared in the App's `AndroidManifest.xml` at compile time. Learn more about the declared permissions [here](http://developer.mocaplatform.com/v2/page/android-included-permissions). [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": "import com.innoquant.moca.MOCA;\nimport com.innoquant.moca.MOCAInstance;\n\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 proximity events when the `Activity` is not running (App not in foreground, for instance)." } [/block]
[block:api-header] { "type": "basic", "title": "Installing Google Play Services." } [/block] MOCA SDK requires Google Play Services 8.3.0+ as you've seen in the dependencies list above. If your project is not using Google Play Services, please ensure the libraries are installed in your Android Studio before continuing. You can see how to install Google Play Services by visiting this [Google guide](https://developer.android.com/studio/intro/update.html). The two mandatory [Google Play Services](https://developers.google.com/android/guides/setup) required are: * com.google.android.gms:play-services-location:15.0.1 * com.google.android.gms:play-services-gcm:15.0.1 [block:api-header] { "type": "basic", "title": "Grab your AppKey and AppSecret" } [/block] 1 - Go to 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": "Option A: Configuration through 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#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\n# Custom settings\n# Save custom settings by adding \"custom.\" prefix\n# example custom.myCustomSetting = 1000\ncustom.myCustomSetting = 1000\n# Legacy notation\nmoca.CUSTOM_PUSH_ICON = @drawable/ic_moca_logo\n# moca.CUSTOM_NAOMICRO_APP_KEY = xxxxxx\n# moca.CUSTOM_NAOMICRO_ENABLED = false\n", "language": "ruby", "name": "MOCA.properties" } ] } [/block] [block:api-header] { "type": "basic", "title": "Option B: Configuration through `AndroidManifest.xml` file" } [/block] - SDK Settings: you don't need to use this keys if you have used a `MOCA.properties` file. [block:callout] { "type": "warning", "body": "Remember to paste the `moca.APP_KEY` and `moca.APP_SECRET` with the ones of your App. Otherwise the SDK won't be able to connect to MOCA Cloud." } [/block] [block:code] { "codes": [ { "code": "<application\n ...>\n <!-- MOCA SDK configuration -->\n <meta-data android:name=\"moca.APP_KEY\"\n android:value=\"YOUR-MOCA-APP-KEY\"/>\n <meta-data android:name=\"moca.APP_SECRET\"\n android:value=\"YOUR-MOCA-APP-SECRET\"/>\n <meta-data android:name=\"moca.LOG_LEVEL\"\n android:value=\"debug\"/>\n <meta-data android:name=\"moca.AUTOMATIC_PUSH_SETUP_ENABLED\"\n android:value=\"true\"/>\n <meta-data android:name=\"moca.PROXIMITY_SERVICE_ENABLED\"\n android:value=\"true\" />\n <meta-data android:name=\"moca.GEOLOCATION_SERVICE_ENABLED\"\n android:value=\"true\" />\n <meta-data android:name=\"moca.BACKGROUND_LOCATION_ENABLED\"\n android:value=\"true\" />\n <meta-data android:name=\"moca.DATA_FETCH_INTERVAL_MS\"\n android:value=\"auto\" />\n <meta-data android:name=\"moca.EVENT_UPLOAD_INTERVAL_MS\"\n android:value=\"auto\" />\n \t<meta-data android:name=\"moca.MOCA_DRIVER_ENABLED\"\n android:value=\"true\" />\n <!--Optional: Include it for remote push notifications-->\n <!--Be careful with the space before the number-->\n <meta-data android:name=\"moca.GCM_SENDER\"\n android:value=\"\\ YOUR_GCM_SENDER_ID\" />\n</application>", "language": "xml" } ] } [/block] - Be sure to replace `moca.APP_KEY` and `moca.APP_SECRET` values with the real values for your app which you found in the MOCA console. Change any setting that you need for your app: - `moca.PROXIMITY_SERVICE_ENABLED`, will enable or disable Bluetooth Beacon detection & geofence detection. - `moca.GEOLOCATION_SERVICE_ENABLED` – enables/disabled tracking of significant changes in user location by GPS/Cellular Trilateration/Wifi. - 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. - NO – user location will not be tracked at all (either foreground nor background). Bluetooth beacons and geofences will still be detected if this flag is set to NO. - `moca.BACKGROUND_LOCATION_ENABLED` – enables/disables location tracking when the app is in background or suspended mode. - This flag has no effect if GEOLOCATION_SERVICE_ENABLED is set to NO. - By default background location tracking is enabled. [block:api-header] { "type": "basic", "title": "Android Marshmallow (6.0) permissions" } [/block] Request the `ACCESS_FINE_LOCATION` permission at Run Time, an example of how to do it is [available here.](doc:android-60-permissions). [block:callout] { "type": "danger", "title": "Needed for bluetooth scanning, Wi-Fi Scanning and Location updates", "body": "Starting from Android M (6.0+), bluetooth beacons, Wi-Fi Networks, Geofences and location updates are not available if the user does not grant this permission. Please make sure you explain to the user why you need the permission before requesting it, this way you will significantly increase your location-aware audience." } [/block] MOCA SDK requires other permissions that are automatically declared in the App's `AndroidManifest.xml` at compile time. Learn more about the declared permissions [here](http://developer.mocaplatform.com/v2/page/android-included-permissions). [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": "import com.innoquant.moca.MOCA;\nimport com.innoquant.moca.MOCAInstance;\n\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 proximity events when the `Activity` is not running (App not in foreground, for instance)." } [/block]
{"_id":"59198f26eba9ac3100018665","user":"559a618bdbcfd20d00710b38","excerpt":"","githubsync":"","title":"Push Notifications","type":"basic","updates":[],"body":"MOCA SDK easily integrates with GCM push notifications.\n\n- GCM 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 \nIf your app already uses push notification, you must *disable* automatic GCM push registration in MOCA.\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]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"NOTE\",\n  \"body\": \"For the `AndroidManifest.xml configuration, 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]","slug":"push-notifications","sync_unique":"","version":"59198f1eeba9ac31000185de","__v":0,"category":"59198f20eba9ac31000185e2","next":{"pages":[],"description":""},"order":2,"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,"childrenPages":[]}

Push Notifications


MOCA SDK easily integrates with GCM push notifications. - GCM 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) - If your app already uses push notification, you must *disable* automatic GCM push registration in MOCA. [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": "danger", "title": "NOTE", "body": "For the `AndroidManifest.xml configuration, 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]
MOCA SDK easily integrates with GCM push notifications. - GCM 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) - If your app already uses push notification, you must *disable* automatic GCM push registration in MOCA. [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": "danger", "title": "NOTE", "body": "For the `AndroidManifest.xml configuration, 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]
{"_id":"59198f26eba9ac3100018666","sync_unique":"","title":"ProGuard rules","updates":[],"__v":0,"githubsync":"","link_external":false,"order":3,"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-keep class javassist.util.** { *; }\n-keep class javassist.tools.** { *; }\n-dontwarn org.msgpack.**\n-dontwarn javassist.util.**\n-dontwarn javassist.tools.**\n```","createdAt":"2016-03-01T17:53:49.824Z","isReference":false,"slug":"proguard-rules","next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","user":"559a618bdbcfd20d00710b38","type":"basic","version":"59198f1eeba9ac31000185de","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]}},"category":"59198f20eba9ac31000185e2","excerpt":"","hidden":false,"link_url":"","childrenPages":[]}

ProGuard rules


If you use ProGuard, please include the following rules: ``` -keep class com.innoquant.** { *; } -keep class org.msgpack.** { *; } -keep class javassist.util.** { *; } -keep class javassist.tools.** { *; } -dontwarn org.msgpack.** -dontwarn javassist.util.** -dontwarn javassist.tools.** ```
If you use ProGuard, please include the following rules: ``` -keep class com.innoquant.** { *; } -keep class org.msgpack.** { *; } -keep class javassist.util.** { *; } -keep class javassist.tools.** { *; } -dontwarn org.msgpack.** -dontwarn javassist.util.** -dontwarn javassist.tools.** ```
{"_id":"59198f26eba9ac3100018667","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":4,"user":"559a618bdbcfd20d00710b38","version":"59198f1eeba9ac31000185de","__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**. Request this permission in your Main Activity this way:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"final int REQUEST_PERMISSION_GEO = 101;        \\nfinal String FINE_LOCATION_PERMISSION = android.Manifest.permission.ACCESS_FINE_LOCATION;\\n\\n\\n@TargetApi(Build.VERSION_CODES.M)\\nprivate void requestMocaPermissions() {\\n  final int permStatus = ContextCompat.checkSelfPermission(this, FINE_LOCATION_PERMISSION);\\n  if (permStatus != PackageManager.PERMISSION_GRANTED) {\\n    if (shouldShowRequestPermissionRationale(FINE_LOCATION_PERMISSION)) {\\n\\n      AlertDialog.Builder builder = new AlertDialog.Builder(this);\\n\\n      builder.setMessage(R.string.LOCATION_PERMISSION_DESCRIPTION)\\n        .setTitle(R.string.APP_SHORT_NAME)\\n        .setNeutralButton(R.string.OK_TEXT, new DialogInterface.OnClickListener() {\\n\\n          public void onClick(DialogInterface dialog, int which) {\\n            requestPermissions(new String[]{FINE_LOCATION_PERMISSION},\\n                               REQUEST_PERMISSION_GEO);\\n          }\\n\\n        }).show();\\n\\n    } else {\\n      // No explanation needed, we can request the permission.\\n      requestPermissions(new String[]{FINE_LOCATION_PERMISSION},\\n                         REQUEST_PERMISSION_GEO);\\n    }\\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 `onRequestPermissionsResult` callback. Below 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, @NonNull String[] permissions,\\n                                           @NonNull int[] grantResults) {\\n\\n        if((requestCode == REQUEST_PERMISSION_GEO)\\n                && (permissions[0].equals(FINE_LOCATION_PERMISSION))\\n                && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){\\n            if(MOCA.initialized()){\\n                MOCA.setProximityEnabled(true);\\n                MOCA.setGeoTrackingEnabled(true);\\n            }\\n        }\\n        else{\\n            Log.e(\\\"MOCA\\\", \\\"Location permission denied by the user.\\\");\\n        }\\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":"59198f20eba9ac31000185e2","title":"Android 6.0+ 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":"","childrenPages":[]}

Android 6.0+ 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**. Request this permission in your Main Activity this way: [block:code] { "codes": [ { "code": "final int REQUEST_PERMISSION_GEO = 101; \nfinal String FINE_LOCATION_PERMISSION = android.Manifest.permission.ACCESS_FINE_LOCATION;\n\n\n@TargetApi(Build.VERSION_CODES.M)\nprivate void requestMocaPermissions() {\n final int permStatus = ContextCompat.checkSelfPermission(this, FINE_LOCATION_PERMISSION);\n if (permStatus != PackageManager.PERMISSION_GRANTED) {\n if (shouldShowRequestPermissionRationale(FINE_LOCATION_PERMISSION)) {\n\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n\n builder.setMessage(R.string.LOCATION_PERMISSION_DESCRIPTION)\n .setTitle(R.string.APP_SHORT_NAME)\n .setNeutralButton(R.string.OK_TEXT, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n requestPermissions(new String[]{FINE_LOCATION_PERMISSION},\n REQUEST_PERMISSION_GEO);\n }\n\n }).show();\n\n } else {\n // No explanation needed, we can request the permission.\n requestPermissions(new String[]{FINE_LOCATION_PERMISSION},\n REQUEST_PERMISSION_GEO);\n }\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 `onRequestPermissionsResult` callback. 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, @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n\n if((requestCode == REQUEST_PERMISSION_GEO)\n && (permissions[0].equals(FINE_LOCATION_PERMISSION))\n && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){\n if(MOCA.initialized()){\n MOCA.setProximityEnabled(true);\n MOCA.setGeoTrackingEnabled(true);\n }\n }\n else{\n Log.e(\"MOCA\", \"Location permission denied by the user.\");\n }\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**. Request this permission in your Main Activity this way: [block:code] { "codes": [ { "code": "final int REQUEST_PERMISSION_GEO = 101; \nfinal String FINE_LOCATION_PERMISSION = android.Manifest.permission.ACCESS_FINE_LOCATION;\n\n\n@TargetApi(Build.VERSION_CODES.M)\nprivate void requestMocaPermissions() {\n final int permStatus = ContextCompat.checkSelfPermission(this, FINE_LOCATION_PERMISSION);\n if (permStatus != PackageManager.PERMISSION_GRANTED) {\n if (shouldShowRequestPermissionRationale(FINE_LOCATION_PERMISSION)) {\n\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n\n builder.setMessage(R.string.LOCATION_PERMISSION_DESCRIPTION)\n .setTitle(R.string.APP_SHORT_NAME)\n .setNeutralButton(R.string.OK_TEXT, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n requestPermissions(new String[]{FINE_LOCATION_PERMISSION},\n REQUEST_PERMISSION_GEO);\n }\n\n }).show();\n\n } else {\n // No explanation needed, we can request the permission.\n requestPermissions(new String[]{FINE_LOCATION_PERMISSION},\n REQUEST_PERMISSION_GEO);\n }\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 `onRequestPermissionsResult` callback. 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, @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n\n if((requestCode == REQUEST_PERMISSION_GEO)\n && (permissions[0].equals(FINE_LOCATION_PERMISSION))\n && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){\n if(MOCA.initialized()){\n MOCA.setProximityEnabled(true);\n MOCA.setGeoTrackingEnabled(true);\n }\n }\n else{\n Log.e(\"MOCA\", \"Location permission denied by the user.\");\n }\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":"59198f26eba9ac3100018669","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":6,"project":"559a61d2dbcfd20d00710b39","type":"basic","user":"559a618bdbcfd20d00710b38","version":"59198f1eeba9ac31000185de","__v":0,"category":"59198f20eba9ac31000185e2","createdAt":"2016-09-13T15:55:17.844Z","excerpt":"","link_external":false,"next":{"pages":[],"description":""},"title":"GCM / FCM: Cloud Messaging Setup.","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":"59198f26eba9ac3100018662","__v":0,"body":"[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/f269600-compatibilityChartMOCASDK.png\",\n        \"compatibilityChartMOCASDK.png\",\n        1445,\n        1141,\n        \"#94173f\"\n      ]\n    }\n  ]\n}\n[/block]","hidden":false,"sync_unique":"","type":"basic","api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","isReference":false,"project":"559a61d2dbcfd20d00710b39","slug":"moca-android-sdk-compatibility-chart","updates":[],"category":"59198f20eba9ac31000185e2","createdAt":"2015-07-17T14:54:34.609Z","link_external":false,"title":"Android compatibility chart","version":"59198f1eeba9ac31000185de","githubsync":"","link_url":"","next":{"pages":[],"description":""},"order":7,"parentDoc":null,"user":"559a618bdbcfd20d00710b38","childrenPages":[]}

Android compatibility chart


[block:image] { "images": [ { "image": [ "https://files.readme.io/f269600-compatibilityChartMOCASDK.png", "compatibilityChartMOCASDK.png", 1445, 1141, "#94173f" ] } ] } [/block]
[block:image] { "images": [ { "image": [ "https://files.readme.io/f269600-compatibilityChartMOCASDK.png", "compatibilityChartMOCASDK.png", 1445, 1141, "#94173f" ] } ] } [/block]
{"_id":"59198f26eba9ac3100018658","category":"59198f20eba9ac31000185e3","isReference":false,"type":"basic","title":"MOCA API","updates":[],"user":"559a618bdbcfd20d00710b38","createdAt":"2015-07-17T16:43:41.170Z","parentDoc":null,"project":"559a61d2dbcfd20d00710b39","sync_unique":"","link_external":false,"next":{"pages":[],"description":""},"__v":0,"body":"The `MOCA static class` is a main entry point to MOCA APIs.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\n\\t/**\\n\\t * Returns the current MOCA SDK version.\\n\\t * \\n\\t * @return The version of the MOCA SDK library.\\n\\t */\\n\\tpublic static String getVersion()\\n\\t\\n\\t/**\\n\\t * Return the key of this application in MOCA service.\\n\\t * \\n\\t * @return MOCA app key.\\n\\t */\\n\\tpublic static String getAppKey()\\n\\t\\n\\t/**\\n\\t * Return the secret key of this application in MOCA service.\\n\\t * \\n\\t * @return MOCA app secret.\\n\\t */\\n\\tpublic static String getAppSecret()\\n\\t\\n\\t/**\\n\\t * Gets the level of logging that will be displayed.\\n\\t */\\n\\tpublic static MOCALogLevel getLogLevel()\\n\\n\\t/**\\n\\t * Returns the current Application.\\n\\t * \\n\\t * @return The current application.\\n\\t */\\n\\tpublic static Application getApplication () \\n\\n  /**\\n   * Gets instance object.\\n   */\\n  public static MOCAInstance getInstance ()\\n \\n\\t/**\\n\\t * Provides access to MOCA Proximity Service. This service is only available\\n\\t * on Android 4.4 and newer.\\n\\t * \\n\\t * @return MOCAProximityService instance or null if it is not available or\\n\\t *         has not been initialized.\\n\\t */\\n\\tpublic static MOCAProximityService getProximityService()\\n\\n\\t/**\\n\\t * Returns true if MOCA Proximity Service is available on this device.\\n\\t * \\n\\t * @return true if the proximity service is available on this device.\\n     * Note: it can be disabled by configuration.\\n\\t */\\n\\tpublic static boolean isProximityAvailable()\\n\\n  /**\\n   * Returns true if MOCA Proximity Service is available and enabled.\\n   *\\n   * @return true if the proximity service is enabled, or false otherwise.\\n   */\\n  public static boolean proximityEnabled ()\\n\\n  /**\\n   * Starts/stops MOCA Proximity service.\\n   * @param enable\\n   */\\n  public static void setProximityEnabled (boolean enable) \\n\\n  private static final String\\tMOCA_AUTOINIT_ON_PUSH_KEY\\t= \\\"MOCA_AUTO_INIT_ON_PUSH\\\";\\n\\n  /**\\n   * Global settings. Enables MOCA to auto-initialize SDK on certain events.\\n   */\\n  public static void setAutoInitOnPush (Context context, boolean enable)\\n    \\n  public static boolean getAutoInitOnPush (Context context)\\n\\t\\n  /**\\n\\t * Tracks a custom in-app event.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb)\\n\\t\\n\\t/**\\n\\t * Tracks an event.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @param value Value associated with the event.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb, long value)\\n\\n\\t/**\\n\\t * Tracks an event.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @param item Item associated with the event.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb, final String item)\\n\\n\\t/**\\n\\t * Tracks an event.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @param item Item associated with the event.\\n\\t * @param value Value associated with the event.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb, final String item, final long value)\\n\\n\\t/**\\n\\t * Tracks an event.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @param item Item associated with the event.\\n\\t * @param category Category the item belongs to.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb, final String category, final String item)\\n\\n\\t/**\\n\\t * Tracks an event.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @param item Item associated with the event.\\n\\t * @param category Category the item belongs to.\\n\\t * @param value Value associated with the event.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb, final String category, final String item, final long value)\\n\\n\\t/**\\n\\t * Tracks an event with custom attributes.\\n\\t * \\n\\t * @param verb Action verb.\\n\\t * @param attrs Collection of attributes associated with this event (up to\\n\\t *            10). Value types are restricted to: {@link String},\\n\\t *            {@link Integer}, {@link Long}, {@link Double}, {@link Float},\\n\\t *            {@link Date} and {@link Location}.\\n\\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\\n\\t *         error.\\n\\t */\\n\\tpublic static boolean track(final String verb, final Map<String, Object> attrs)\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nStart / Stop specific MOCA SDK Services.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n* Returns true if MOCA Event Tracking service is enabled.\\n*/\\nstatic boolean\\teventTrackingEnabled();\\n\\n/**\\n* Starts/stops MOCA Event Tracking service..\\n*/\\nstatic void\\tsetEventTrackingEnabled(boolean enabled)\\n\\n/**\\n* Returns true if MOCA Remote Push Notification service (GCM) is available and * * enabled.\\n*/\\nstatic boolean\\tremotePushEnabled();\\n\\n/**\\n* Starts/stops MOCA Remote Push Notification service (GCM)\\n*/\\nstatic void\\tsetRemotePushEnabled(boolean enabled)\\n\\n/**\\n* Returns true if MOCA Geolocation Tracking service is available and enabled\\n*/\\nstatic boolean\\tgeoTrackingEnabled()\\n\\n/**\\n* Starts/stops MOCA Geolocation Tracking service.\\n*/\\nstatic void\\tsetGeoTrackingEnabled(boolean enabled)\\n\\n/**\\n* Returns true if MOCA Proximity Service is available and enabled.\\n*/\\nstatic boolean\\tproximityEnabled()\\n\\n/**\\n* Starts/stops MOCA Proximity service.\\n*/\\nstatic void\\tsetProximityEnabled(boolean enabled)\\n\\n/**\\n* Returns true if the \\\"Wifi Only\\\" data transmission setting is activated\\n*/\\nstatic boolean\\tisWifiOnlyEnabled() \\n\\n/**\\n* If true, limits data transmission to Wifi only\\n*/\\nstatic void\\tsetWifiOnlyEnabled(boolean enabled)\\n  \\n/**\\n* Returns true if the indoor location analytics service is active\\n*/\\nstatic boolean\\tisIndoorAnalyticsEnabled() \\n\\n /**\\n * If true, starts tracking data generated by the indoor location engine\\n * (if any)\\n */\\nstatic void\\tsetIndoorAnalyticsEnabled(boolean enabled) \\n\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","githubsync":"","hidden":false,"slug":"moca-api","version":"59198f1eeba9ac31000185de","api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","link_url":"","order":0,"childrenPages":[]}

MOCA API


The `MOCA static class` is a main entry point to MOCA APIs. [block:code] { "codes": [ { "code": "\n\t/**\n\t * Returns the current MOCA SDK version.\n\t * \n\t * @return The version of the MOCA SDK library.\n\t */\n\tpublic static String getVersion()\n\t\n\t/**\n\t * Return the key of this application in MOCA service.\n\t * \n\t * @return MOCA app key.\n\t */\n\tpublic static String getAppKey()\n\t\n\t/**\n\t * Return the secret key of this application in MOCA service.\n\t * \n\t * @return MOCA app secret.\n\t */\n\tpublic static String getAppSecret()\n\t\n\t/**\n\t * Gets the level of logging that will be displayed.\n\t */\n\tpublic static MOCALogLevel getLogLevel()\n\n\t/**\n\t * Returns the current Application.\n\t * \n\t * @return The current application.\n\t */\n\tpublic static Application getApplication () \n\n /**\n * Gets instance object.\n */\n public static MOCAInstance getInstance ()\n \n\t/**\n\t * Provides access to MOCA Proximity Service. This service is only available\n\t * on Android 4.4 and newer.\n\t * \n\t * @return MOCAProximityService instance or null if it is not available or\n\t * has not been initialized.\n\t */\n\tpublic static MOCAProximityService getProximityService()\n\n\t/**\n\t * Returns true if MOCA Proximity Service is available on this device.\n\t * \n\t * @return true if the proximity service is available on this device.\n * Note: it can be disabled by configuration.\n\t */\n\tpublic static boolean isProximityAvailable()\n\n /**\n * Returns true if MOCA Proximity Service is available and enabled.\n *\n * @return true if the proximity service is enabled, or false otherwise.\n */\n public static boolean proximityEnabled ()\n\n /**\n * Starts/stops MOCA Proximity service.\n * @param enable\n */\n public static void setProximityEnabled (boolean enable) \n\n private static final String\tMOCA_AUTOINIT_ON_PUSH_KEY\t= \"MOCA_AUTO_INIT_ON_PUSH\";\n\n /**\n * Global settings. Enables MOCA to auto-initialize SDK on certain events.\n */\n public static void setAutoInitOnPush (Context context, boolean enable)\n \n public static boolean getAutoInitOnPush (Context context)\n\t\n /**\n\t * Tracks a custom in-app event.\n\t * \n\t * @param verb Action verb.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb)\n\t\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param value Value associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, long value)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String item)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @param value Value associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String item, final long value)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @param category Category the item belongs to.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String category, final String item)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @param category Category the item belongs to.\n\t * @param value Value associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String category, final String item, final long value)\n\n\t/**\n\t * Tracks an event with custom attributes.\n\t * \n\t * @param verb Action verb.\n\t * @param attrs Collection of attributes associated with this event (up to\n\t * 10). Value types are restricted to: {@link String},\n\t * {@link Integer}, {@link Long}, {@link Double}, {@link Float},\n\t * {@link Date} and {@link Location}.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final Map<String, Object> attrs)\n", "language": "java" } ] } [/block] Start / Stop specific MOCA SDK Services. [block:code] { "codes": [ { "code": "/**\n* Returns true if MOCA Event Tracking service is enabled.\n*/\nstatic boolean\teventTrackingEnabled();\n\n/**\n* Starts/stops MOCA Event Tracking service..\n*/\nstatic void\tsetEventTrackingEnabled(boolean enabled)\n\n/**\n* Returns true if MOCA Remote Push Notification service (GCM) is available and * * enabled.\n*/\nstatic boolean\tremotePushEnabled();\n\n/**\n* Starts/stops MOCA Remote Push Notification service (GCM)\n*/\nstatic void\tsetRemotePushEnabled(boolean enabled)\n\n/**\n* Returns true if MOCA Geolocation Tracking service is available and enabled\n*/\nstatic boolean\tgeoTrackingEnabled()\n\n/**\n* Starts/stops MOCA Geolocation Tracking service.\n*/\nstatic void\tsetGeoTrackingEnabled(boolean enabled)\n\n/**\n* Returns true if MOCA Proximity Service is available and enabled.\n*/\nstatic boolean\tproximityEnabled()\n\n/**\n* Starts/stops MOCA Proximity service.\n*/\nstatic void\tsetProximityEnabled(boolean enabled)\n\n/**\n* Returns true if the \"Wifi Only\" data transmission setting is activated\n*/\nstatic boolean\tisWifiOnlyEnabled() \n\n/**\n* If true, limits data transmission to Wifi only\n*/\nstatic void\tsetWifiOnlyEnabled(boolean enabled)\n \n/**\n* Returns true if the indoor location analytics service is active\n*/\nstatic boolean\tisIndoorAnalyticsEnabled() \n\n /**\n * If true, starts tracking data generated by the indoor location engine\n * (if any)\n */\nstatic void\tsetIndoorAnalyticsEnabled(boolean enabled) \n\n", "language": "java" } ] } [/block]
The `MOCA static class` is a main entry point to MOCA APIs. [block:code] { "codes": [ { "code": "\n\t/**\n\t * Returns the current MOCA SDK version.\n\t * \n\t * @return The version of the MOCA SDK library.\n\t */\n\tpublic static String getVersion()\n\t\n\t/**\n\t * Return the key of this application in MOCA service.\n\t * \n\t * @return MOCA app key.\n\t */\n\tpublic static String getAppKey()\n\t\n\t/**\n\t * Return the secret key of this application in MOCA service.\n\t * \n\t * @return MOCA app secret.\n\t */\n\tpublic static String getAppSecret()\n\t\n\t/**\n\t * Gets the level of logging that will be displayed.\n\t */\n\tpublic static MOCALogLevel getLogLevel()\n\n\t/**\n\t * Returns the current Application.\n\t * \n\t * @return The current application.\n\t */\n\tpublic static Application getApplication () \n\n /**\n * Gets instance object.\n */\n public static MOCAInstance getInstance ()\n \n\t/**\n\t * Provides access to MOCA Proximity Service. This service is only available\n\t * on Android 4.4 and newer.\n\t * \n\t * @return MOCAProximityService instance or null if it is not available or\n\t * has not been initialized.\n\t */\n\tpublic static MOCAProximityService getProximityService()\n\n\t/**\n\t * Returns true if MOCA Proximity Service is available on this device.\n\t * \n\t * @return true if the proximity service is available on this device.\n * Note: it can be disabled by configuration.\n\t */\n\tpublic static boolean isProximityAvailable()\n\n /**\n * Returns true if MOCA Proximity Service is available and enabled.\n *\n * @return true if the proximity service is enabled, or false otherwise.\n */\n public static boolean proximityEnabled ()\n\n /**\n * Starts/stops MOCA Proximity service.\n * @param enable\n */\n public static void setProximityEnabled (boolean enable) \n\n private static final String\tMOCA_AUTOINIT_ON_PUSH_KEY\t= \"MOCA_AUTO_INIT_ON_PUSH\";\n\n /**\n * Global settings. Enables MOCA to auto-initialize SDK on certain events.\n */\n public static void setAutoInitOnPush (Context context, boolean enable)\n \n public static boolean getAutoInitOnPush (Context context)\n\t\n /**\n\t * Tracks a custom in-app event.\n\t * \n\t * @param verb Action verb.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb)\n\t\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param value Value associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, long value)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String item)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @param value Value associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String item, final long value)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @param category Category the item belongs to.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String category, final String item)\n\n\t/**\n\t * Tracks an event.\n\t * \n\t * @param verb Action verb.\n\t * @param item Item associated with the event.\n\t * @param category Category the item belongs to.\n\t * @param value Value associated with the event.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final String category, final String item, final long value)\n\n\t/**\n\t * Tracks an event with custom attributes.\n\t * \n\t * @param verb Action verb.\n\t * @param attrs Collection of attributes associated with this event (up to\n\t * 10). Value types are restricted to: {@link String},\n\t * {@link Integer}, {@link Long}, {@link Double}, {@link Float},\n\t * {@link Date} and {@link Location}.\n\t * @return <code>YES</code> in case of success, <code>NO</code> in case of\n\t * error.\n\t */\n\tpublic static boolean track(final String verb, final Map<String, Object> attrs)\n", "language": "java" } ] } [/block] Start / Stop specific MOCA SDK Services. [block:code] { "codes": [ { "code": "/**\n* Returns true if MOCA Event Tracking service is enabled.\n*/\nstatic boolean\teventTrackingEnabled();\n\n/**\n* Starts/stops MOCA Event Tracking service..\n*/\nstatic void\tsetEventTrackingEnabled(boolean enabled)\n\n/**\n* Returns true if MOCA Remote Push Notification service (GCM) is available and * * enabled.\n*/\nstatic boolean\tremotePushEnabled();\n\n/**\n* Starts/stops MOCA Remote Push Notification service (GCM)\n*/\nstatic void\tsetRemotePushEnabled(boolean enabled)\n\n/**\n* Returns true if MOCA Geolocation Tracking service is available and enabled\n*/\nstatic boolean\tgeoTrackingEnabled()\n\n/**\n* Starts/stops MOCA Geolocation Tracking service.\n*/\nstatic void\tsetGeoTrackingEnabled(boolean enabled)\n\n/**\n* Returns true if MOCA Proximity Service is available and enabled.\n*/\nstatic boolean\tproximityEnabled()\n\n/**\n* Starts/stops MOCA Proximity service.\n*/\nstatic void\tsetProximityEnabled(boolean enabled)\n\n/**\n* Returns true if the \"Wifi Only\" data transmission setting is activated\n*/\nstatic boolean\tisWifiOnlyEnabled() \n\n/**\n* If true, limits data transmission to Wifi only\n*/\nstatic void\tsetWifiOnlyEnabled(boolean enabled)\n \n/**\n* Returns true if the indoor location analytics service is active\n*/\nstatic boolean\tisIndoorAnalyticsEnabled() \n\n /**\n * If true, starts tracking data generated by the indoor location engine\n * (if any)\n */\nstatic void\tsetIndoorAnalyticsEnabled(boolean enabled) \n\n", "language": "java" } ] } [/block]
{"_id":"59198f26eba9ac3100018659","api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"user":"559a618bdbcfd20d00710b38","parentDoc":null,"slug":"instance-api-1","title":"Instance API","type":"basic","hidden":false,"project":"559a61d2dbcfd20d00710b39","version":"59198f1eeba9ac31000185de","githubsync":"","order":1,"category":"59198f20eba9ac31000185e3","createdAt":"2015-07-17T16:51:59.713Z","excerpt":"","isReference":false,"link_external":false,"link_url":"","__v":0,"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\": \"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\": \"/*Returns true if this map contains a mapping for the specified key.*/\\ncontainsProperty(java.lang.String key)\\n\\n/*Returns the Object Array value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetArrayProperty(java.lang.String key)\\n\\n/*Returns the Boolean value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetBoolProperty(java.lang.String key)\\n\\n/*Returns the Float value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetFloatProperty(java.lang.String key)\\n  \\n/*Returns the Integer value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetIntegerProperty(java.lang.String key)\\n  \\n/*Returns the long value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetLongProperty(java.lang.String key)\\n  \\n/*Returns the value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetProperty(java.lang.String key)\\n\\n/*Returns the String Array value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetStringArrayProperty(java.lang.String key)\\n  \\n/*Returns the String value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\\ngetStringProperty(java.lang.String key)\\n\\n/*Gets existing property keys.*/\\npropertySet()\\n  \\n/*Associates the specified property value with the specified property key in this container.*/\\nsetProperty(java.lang.String key, java.lang.Object value)\\n\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nThe instance object holds **predefined properties** collected automatically:\n\n- Device-oriented, including:\n - device_model – the device model (i.e. iPhone 4S, iPhone 5C, iPhone 5S)\n - device_type – the type of device (i.e. iPhone, iPad, Simulator)\n - local_timezone – the local time zone's abbreviated name (i.e. EDT, GMT, PST)\n - country – the country code as defined by the user in Settings\n - lang – the user preferred language code as defined in Settings\n - os_name – the OS name (i.e. “Android”)\n - os_version – the OS version (i.e. “4.4”)\n - carrier_name – the name of the user’s home cellular service provider (E.g. Vodafone)\n - carrier_country – the ISO country code for the user’s cellular service provider.\n- App-oriented, including:\n - app_name – the app name\n - app_version – the app version number\n - vendor_id – the unique identifier for app vendor (i.e. UUID string)\n - moca_version – the version of MOCA SDK\n - gcm_token – the push notification device token (optional)\n - session – session counter (how many times a user launched the app).\n\n\n- The object may also store any custom property-value pairs. \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[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAInstance instance = MOCA.getInstance ();\\n// set MOCA custom properties\\ninstance.setProperty(\\\"job_position\\\", \\\"CTO\\\");\\ninstance.setProperty(”user_identifier\\\", 2948579);\\ninstance.setProperty(”user_score\\\", 147.61);\\ninstance.setProperty(”last_timestamp\\\", System.currentTimeMillis());\\nString[] skills = new String[]{“NoSQL\\\", ”Ruby\\\", “Java\\\", ”Objective-C\\\"};\\ninstance.setProperty(”user_skills\\\", skills );\\n                     // asynchronously upload to cloud\\ninstance.save(new MOCACallback<MOCAInstance>() {\\n                @Override\\n                public void success(MOCAInstance mocaInstance) {\\n                    MLog.i(\\\"Instance uploaded to cloud\\\");\\n                }\\n\\n                @Override\\n                public void failure(MOCAException e) {\\n                    MLog.e(\\\"Instance upload failed\\\", e);\\n                }\\n});\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","updates":[],"next":{"pages":[],"description":""},"sync_unique":"","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": "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": "/*Returns true if this map contains a mapping for the specified key.*/\ncontainsProperty(java.lang.String key)\n\n/*Returns the Object Array value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetArrayProperty(java.lang.String key)\n\n/*Returns the Boolean value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetBoolProperty(java.lang.String key)\n\n/*Returns the Float value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetFloatProperty(java.lang.String key)\n \n/*Returns the Integer value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetIntegerProperty(java.lang.String key)\n \n/*Returns the long value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetLongProperty(java.lang.String key)\n \n/*Returns the value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetProperty(java.lang.String key)\n\n/*Returns the String Array value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetStringArrayProperty(java.lang.String key)\n \n/*Returns the String value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetStringProperty(java.lang.String key)\n\n/*Gets existing property keys.*/\npropertySet()\n \n/*Associates the specified property value with the specified property key in this container.*/\nsetProperty(java.lang.String key, java.lang.Object value)\n\n", "language": "java" } ] } [/block] The instance object holds **predefined properties** collected automatically: - Device-oriented, including: - device_model – the device model (i.e. iPhone 4S, iPhone 5C, iPhone 5S) - device_type – the type of device (i.e. iPhone, iPad, Simulator) - local_timezone – the local time zone's abbreviated name (i.e. EDT, GMT, PST) - country – the country code as defined by the user in Settings - lang – the user preferred language code as defined in Settings - os_name – the OS name (i.e. “Android”) - os_version – the OS version (i.e. “4.4”) - carrier_name – the name of the user’s home cellular service provider (E.g. Vodafone) - carrier_country – the ISO country code for the user’s cellular service provider. - App-oriented, including: - app_name – the app name - app_version – the app version number - vendor_id – the unique identifier for app vendor (i.e. UUID string) - moca_version – the version of MOCA SDK - gcm_token – the push notification device token (optional) - session – session counter (how many times a user launched the app). - The object may also store any custom property-value pairs. - 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 ();\n// set MOCA custom properties\ninstance.setProperty(\"job_position\", \"CTO\");\ninstance.setProperty(”user_identifier\", 2948579);\ninstance.setProperty(”user_score\", 147.61);\ninstance.setProperty(”last_timestamp\", System.currentTimeMillis());\nString[] skills = new String[]{“NoSQL\", ”Ruby\", “Java\", ”Objective-C\"};\ninstance.setProperty(”user_skills\", skills );\n // asynchronously upload to cloud\ninstance.save(new MOCACallback<MOCAInstance>() {\n @Override\n public void success(MOCAInstance mocaInstance) {\n MLog.i(\"Instance uploaded to cloud\");\n }\n\n @Override\n public void failure(MOCAException e) {\n MLog.e(\"Instance upload failed\", e);\n }\n});\n", "language": "java" } ] } [/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": "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": "/*Returns true if this map contains a mapping for the specified key.*/\ncontainsProperty(java.lang.String key)\n\n/*Returns the Object Array value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetArrayProperty(java.lang.String key)\n\n/*Returns the Boolean value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetBoolProperty(java.lang.String key)\n\n/*Returns the Float value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetFloatProperty(java.lang.String key)\n \n/*Returns the Integer value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetIntegerProperty(java.lang.String key)\n \n/*Returns the long value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetLongProperty(java.lang.String key)\n \n/*Returns the value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetProperty(java.lang.String key)\n\n/*Returns the String Array value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetStringArrayProperty(java.lang.String key)\n \n/*Returns the String value to which the specified property key is mapped, or null if this map contains no mapping for the key.*/\ngetStringProperty(java.lang.String key)\n\n/*Gets existing property keys.*/\npropertySet()\n \n/*Associates the specified property value with the specified property key in this container.*/\nsetProperty(java.lang.String key, java.lang.Object value)\n\n", "language": "java" } ] } [/block] The instance object holds **predefined properties** collected automatically: - Device-oriented, including: - device_model – the device model (i.e. iPhone 4S, iPhone 5C, iPhone 5S) - device_type – the type of device (i.e. iPhone, iPad, Simulator) - local_timezone – the local time zone's abbreviated name (i.e. EDT, GMT, PST) - country – the country code as defined by the user in Settings - lang – the user preferred language code as defined in Settings - os_name – the OS name (i.e. “Android”) - os_version – the OS version (i.e. “4.4”) - carrier_name – the name of the user’s home cellular service provider (E.g. Vodafone) - carrier_country – the ISO country code for the user’s cellular service provider. - App-oriented, including: - app_name – the app name - app_version – the app version number - vendor_id – the unique identifier for app vendor (i.e. UUID string) - moca_version – the version of MOCA SDK - gcm_token – the push notification device token (optional) - session – session counter (how many times a user launched the app). - The object may also store any custom property-value pairs. - 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 ();\n// set MOCA custom properties\ninstance.setProperty(\"job_position\", \"CTO\");\ninstance.setProperty(”user_identifier\", 2948579);\ninstance.setProperty(”user_score\", 147.61);\ninstance.setProperty(”last_timestamp\", System.currentTimeMillis());\nString[] skills = new String[]{“NoSQL\", ”Ruby\", “Java\", ”Objective-C\"};\ninstance.setProperty(”user_skills\", skills );\n // asynchronously upload to cloud\ninstance.save(new MOCACallback<MOCAInstance>() {\n @Override\n public void success(MOCAInstance mocaInstance) {\n MLog.i(\"Instance uploaded to cloud\");\n }\n\n @Override\n public void failure(MOCAException e) {\n MLog.e(\"Instance upload failed\", e);\n }\n});\n", "language": "java" } ] } [/block]
{"_id":"59198f26eba9ac310001865a","type":"basic","__v":0,"parentDoc":null,"sync_unique":"","githubsync":"","isReference":false,"link_external":false,"order":2,"project":"559a61d2dbcfd20d00710b39","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.\n\n\nTo access existing *User object*, use currentUser property: \u000b\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Access authenticated user object\\nMOCAUser theUser = MOCA.getInstance().getUser();\\nif (theUser != null) {\\n    // ...\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nTo *authenticate* a new user, use *login(id)* call:\n[block:callout]\n{\n  \"type\": \"warning\",\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 login in the SDK.\",\n  \"title\": \"Login the user with every app startup\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Authenticate a user by unique id\\nMOCAUser theUser = MOCA.getInstance().login(”UNIQUE_USER_ID”);\\n// ...\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nTo **logout** a user, call:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"theUser.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[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"final MOCAUser user = MOCA.getInstance().getUser();\\nuser.setProperty(\\\"member\\\", true);\\nuser.setProperty(\\\"birthYear\\\", 1989);\",\n      \"language\": \"text\"\n    }\n  ]\n}\n[/block]\n- Each user object is **persisted both locally and in the cloud**. \n- Always save the user immediately after login to ensure the data is stored in the cloud as fast as possible.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAUser theUser = MOCA.getInstance().login(\\\"some_unique_id\\\");\\nif (theUser != null) {\\n    theUser.save(new MOCACallback<MOCAUser>() {\\n        @Override\\n        public void success(MOCAUser user) {\\n            Log.i(TAG, \\\"Login successful\\\");\\n        }\\n\\n        @Override\\n        public void failure(MOCAException e) {\\n            Log.e(TAG, \\\"Login failed\\\", e);\\n        }\\n    });\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]","category":"59198f20eba9ac31000185e3","excerpt":"","slug":"user-api-1","next":{"pages":[],"description":""},"title":"User API","version":"59198f1eeba9ac31000185de","createdAt":"2015-07-17T17:17:46.264Z","hidden":false,"user":"559a618bdbcfd20d00710b38","api":{"settings":"","auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]}},"link_url":"","updates":[],"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": "// Access authenticated user object\nMOCAUser theUser = MOCA.getInstance().getUser();\nif (theUser != null) {\n // ...\n}", "language": "java" } ] } [/block] To *authenticate* a new user, use *login(id)* call: [block:callout] { "type": "warning", "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 login in the SDK.", "title": "Login the user with every app startup" } [/block] [block:code] { "codes": [ { "code": "// Authenticate a user by unique id\nMOCAUser theUser = MOCA.getInstance().login(”UNIQUE_USER_ID”);\n// ...\n", "language": "java" } ] } [/block] To **logout** a user, call: [block:code] { "codes": [ { "code": "theUser.logout();", "language": "java" } ] } [/block] - The user object holds a **collection of properties**. Property-value pairs can be set and retrieved. [block:code] { "codes": [ { "code": "final MOCAUser user = MOCA.getInstance().getUser();\nuser.setProperty(\"member\", true);\nuser.setProperty(\"birthYear\", 1989);", "language": "text" } ] } [/block] - Each user object is **persisted both locally and in the cloud**. - Always save the user immediately after login to ensure the data is stored in the cloud as fast as possible. [block:code] { "codes": [ { "code": "MOCAUser theUser = MOCA.getInstance().login(\"some_unique_id\");\nif (theUser != null) {\n theUser.save(new MOCACallback<MOCAUser>() {\n @Override\n public void success(MOCAUser user) {\n Log.i(TAG, \"Login successful\");\n }\n\n @Override\n public void failure(MOCAException e) {\n Log.e(TAG, \"Login failed\", e);\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": "// Access authenticated user object\nMOCAUser theUser = MOCA.getInstance().getUser();\nif (theUser != null) {\n // ...\n}", "language": "java" } ] } [/block] To *authenticate* a new user, use *login(id)* call: [block:callout] { "type": "warning", "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 login in the SDK.", "title": "Login the user with every app startup" } [/block] [block:code] { "codes": [ { "code": "// Authenticate a user by unique id\nMOCAUser theUser = MOCA.getInstance().login(”UNIQUE_USER_ID”);\n// ...\n", "language": "java" } ] } [/block] To **logout** a user, call: [block:code] { "codes": [ { "code": "theUser.logout();", "language": "java" } ] } [/block] - The user object holds a **collection of properties**. Property-value pairs can be set and retrieved. [block:code] { "codes": [ { "code": "final MOCAUser user = MOCA.getInstance().getUser();\nuser.setProperty(\"member\", true);\nuser.setProperty(\"birthYear\", 1989);", "language": "text" } ] } [/block] - Each user object is **persisted both locally and in the cloud**. - Always save the user immediately after login to ensure the data is stored in the cloud as fast as possible. [block:code] { "codes": [ { "code": "MOCAUser theUser = MOCA.getInstance().login(\"some_unique_id\");\nif (theUser != null) {\n theUser.save(new MOCACallback<MOCAUser>() {\n @Override\n public void success(MOCAUser user) {\n Log.i(TAG, \"Login successful\");\n }\n\n @Override\n public void failure(MOCAException e) {\n Log.e(TAG, \"Login failed\", e);\n }\n });\n}", "language": "java" } ] } [/block]
{"_id":"59198f26eba9ac310001865b","createdAt":"2015-07-17T17:21:57.339Z","isReference":false,"parentDoc":null,"slug":"user-profile-1","updates":[],"version":"59198f1eeba9ac31000185de","excerpt":"","hidden":false,"project":"559a61d2dbcfd20d00710b39","title":"User Profile","user":"559a618bdbcfd20d00710b38","category":"59198f20eba9ac31000185e3","link_external":false,"next":{"pages":[],"description":""},"order":3,"type":"basic","__v":0,"api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required"},"body":"- The MOCA SDK, once the user has opted in, passively develops \u000ba **User Profile **of mobile usage and other behaviors.\n- The profile ensures that the app can deliver much more personalized, relevant content based on: \n - Interests – sports, video games, books, cooking\n - Places of Interest (POIs) – top locations where the user spends time (e.g. home, work, restaurant, etc.)\n- User profile is elaborated automatically without user interaction\n- MOCA respects user’s privacy. Contact us for privacy policy recommendations.","githubsync":"","link_url":"","sync_unique":"","childrenPages":[]}

User Profile


- The MOCA SDK, once the user has opted in, passively develops a **User Profile **of mobile usage and other behaviors. - The profile ensures that the app can deliver much more personalized, relevant content based on: - Interests – sports, video games, books, cooking - Places of Interest (POIs) – top locations where the user spends time (e.g. home, work, restaurant, etc.) - User profile is elaborated automatically without user interaction - MOCA respects user’s privacy. Contact us for privacy policy recommendations.
- The MOCA SDK, once the user has opted in, passively develops a **User Profile **of mobile usage and other behaviors. - The profile ensures that the app can deliver much more personalized, relevant content based on: - Interests – sports, video games, books, cooking - Places of Interest (POIs) – top locations where the user spends time (e.g. home, work, restaurant, etc.) - User profile is elaborated automatically without user interaction - MOCA respects user’s privacy. Contact us for privacy policy recommendations.
{"_id":"59198f26eba9ac310001865c","next":{"pages":[],"description":""},"order":4,"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":"59198f20eba9ac31000185e3","isReference":false,"link_external":false,"githubsync":"","hidden":false,"project":"559a61d2dbcfd20d00710b39","slug":"tag-api","user":"559a618bdbcfd20d00710b38","version":"59198f1eeba9ac31000185de","api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"excerpt":"","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":"59198f26eba9ac310001865d","slug":"event-api-1","version":"59198f1eeba9ac31000185de","__v":0,"createdAt":"2015-07-17T17:28:02.199Z","hidden":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","type":"basic","updates":[],"user":"559a618bdbcfd20d00710b38","body":"A single `event object` record contains:\n\n- Event data:\n - Identifier – unique event ID (UUID)\n - Timestamp – GMT timestamp when event occurred\n - Local timestamp – timestamp with local timezone\n - Event type – type of event\n - Action verb – string that describes performed action (i.e. Buy, View, Search, Enter, etc.)\n - Item – item associated with the event (i.e. Product ID)\n - Item Category – category the item belongs to (Product Category)\n - Value – value associated with the event (E.g. purchase amount)\n\n- Context data:\n - Instance ID – the instance object ID that generated the event\n - User ID – the logged-in user that generated the event (optional)\n - Device model/type\n - OS name/version\n - Country\n - Language\n - And other attributes\n\nBy default, the SDK automatically tracks predefined events:\n - _start_session – when the new app session was started\n - _session – when the user’s session ends\n - _geo – track last coordinates of the current location *\n - _visit – when a user visits a frequent place *\n - _push – when push notification has been received while the app was running\n - _launching_push – when app was started by a push notification\n - _action – when proximity action has been triggered\n - _beacon_proximity – when the device entered/exited a beacon region *\n - _zone_proximity – when the device entered/exited a proximity zone *\n - _place_proximity – when the device entered/exited a proximity place *\n - _tick – indicates if the app is active\n - _user_login – when user logged in\n - _user_logout – when user logged out\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"`*` Used when available and allowed by user privacy settings.\",\n  \"sidebar\": true\n}\n[/block]\nTo 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":"59198f20eba9ac31000185e3","excerpt":"","order":5,"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","childrenPages":[]}

Event API


A single `event object` record contains: - Event data: - Identifier – unique event ID (UUID) - Timestamp – GMT timestamp when event occurred - Local timestamp – timestamp with local timezone - Event type – type of event - Action verb – string that describes performed action (i.e. Buy, View, Search, Enter, etc.) - Item – item associated with the event (i.e. Product ID) - Item Category – category the item belongs to (Product Category) - Value – value associated with the event (E.g. purchase amount) - Context data: - Instance ID – the instance object ID that generated the event - User ID – the logged-in user that generated the event (optional) - Device model/type - OS name/version - Country - Language - And other attributes By default, the SDK automatically tracks predefined events: - _start_session – when the new app session was started - _session – when the user’s session ends - _geo – track last coordinates of the current location * - _visit – when a user visits a frequent place * - _push – when push notification has been received while the app was running - _launching_push – when app was started by a push notification - _action – when proximity action has been triggered - _beacon_proximity – when the device entered/exited a beacon region * - _zone_proximity – when the device entered/exited a proximity zone * - _place_proximity – when the device entered/exited a proximity place * - _tick – indicates if the app is active - _user_login – when user logged in - _user_logout – when user logged out [block:callout] { "type": "warning", "body": "`*` Used when available and allowed by user privacy settings.", "sidebar": true } [/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]
A single `event object` record contains: - Event data: - Identifier – unique event ID (UUID) - Timestamp – GMT timestamp when event occurred - Local timestamp – timestamp with local timezone - Event type – type of event - Action verb – string that describes performed action (i.e. Buy, View, Search, Enter, etc.) - Item – item associated with the event (i.e. Product ID) - Item Category – category the item belongs to (Product Category) - Value – value associated with the event (E.g. purchase amount) - Context data: - Instance ID – the instance object ID that generated the event - User ID – the logged-in user that generated the event (optional) - Device model/type - OS name/version - Country - Language - And other attributes By default, the SDK automatically tracks predefined events: - _start_session – when the new app session was started - _session – when the user’s session ends - _geo – track last coordinates of the current location * - _visit – when a user visits a frequent place * - _push – when push notification has been received while the app was running - _launching_push – when app was started by a push notification - _action – when proximity action has been triggered - _beacon_proximity – when the device entered/exited a beacon region * - _zone_proximity – when the device entered/exited a proximity zone * - _place_proximity – when the device entered/exited a proximity place * - _tick – indicates if the app is active - _user_login – when user logged in - _user_logout – when user logged out [block:callout] { "type": "warning", "body": "`*` Used when available and allowed by user privacy settings.", "sidebar": true } [/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":"59198f26eba9ac310001865e","createdAt":"2015-07-17T17:37:16.339Z","order":6,"type":"basic","updates":[],"version":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e3","isReference":false,"link_url":"","slug":"proximity-api-1","sync_unique":"","user":"559a618bdbcfd20d00710b38","__v":0,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"parentDoc":null,"link_external":false,"next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","title":"Proximity API","body":"##Introduction\n\n- The *MOCA SDK* lets you effortlessly add Bluetooth beacon based proximity experiences to your Android app.\n- The SDK comes with a powerful proximity engine based on Complex Event Processing logic (see CEP).\n- MOCA defines some fundamental concepts:\n - Place, Zone, and Beacon\n - Trigger and Action\n - Visit\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/WLyeYphSEG6RZQzRWIvs_Da-proximity-experience.png\",\n        \"Da-proximity-experience.png\",\n        \"911\",\n        \"457\",\n        \"#3ba0da\",\n        \"\"\n      ],\n      \"caption\": \"MOCA Fundamental concepts\"\n    }\n  ]\n}\n[/block]\nTo start using** Beacon-based proximity experiences** in your Android app, you’ll need to enable proximity service.\n\n\n- Ensure proximity service is enabled in `AndroidManifest.xml file\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" <application …>\\n\\n\\t<meta-data android:name=”moca.PROXIMITY_SERVICE_ENABLED\\\" android:value=\\\"true\\\"/>\\n\",\n      \"language\": \"xml\"\n    }\n  ]\n}\n[/block]\n- The MOCA.initializeSDK() call, will automatically start MOCA proximity engine and synchronize proximity campaigns defined in your MOCA cloud account.\n\n###Places\nRepresents a real-world location, such as a store, venue, museum, building, office and so on.\n- A place can be localized by a geo-fence (GPS location and radius in meters) \n- A place contains a collection of zones, where each zone defines semantics for an indoor location, such as Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc.\n\n###Zone\nRepresents a indoor area or micro-location within the place with user-defined semantics. \n- Examples include Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc.\n- A zone is defined by a range of one or more beacon sensors. \n\n###Beacon\nIt is a BLE, iBeacon-compatible proximity sensor.\n- Each beacon is identified by { Proximity UUID, Major and Minor } tuple.\n- MOCA SDK works with any iBeacon-compatible devices. \n - This includes MOCA Beacons \n - And beacons provided by other manufacturers such as Kontakt.io, Estimote, etc.\n- Beacons are assigned to Zones that define their micro-location semantics. \n- Each beacon must be registered in MOCA Management Console.\n\n###Campaigns \nCollections of proximity experiences that are delivered to a user within a specified time frame.\n\n###Experience \nDefines a proximity interaction with a user. \n- An experience is composed of a trigger condition and an action. \n- When proximity trigger conditions are met, the corresponding action is fired.\n\n###Trigger\nIt is a condition or a collection of conditions that must be met to fire an action associated with an experience. For example:\n- Enter place, \n- Exit place, \n- Enter zone, \n- Exit zone,\n- Enter beacon range with given proximity, \n- Exit beacon range,\n- Custom trigger (implemented as app-provided delegate callback)\n\n###Action\nDescribes an activity to be performed when experience trigger conditions are met. The SDK supports the following actions:\n- Show local push notification with a specific message\n- Play sound with a specific file name (included in app bundle)\n- Play video from URL\n- Show image from URL\n- Show HTML content from URL\n- Open custom URL\n- Show PassBook card\n- Custom action (implemented as app-provided delegate callback)","excerpt":"","githubsync":"","hidden":false,"childrenPages":[]}

Proximity API


##Introduction - The *MOCA SDK* lets you effortlessly add Bluetooth beacon based proximity experiences to your Android app. - The SDK comes with a powerful proximity engine based on Complex Event Processing logic (see CEP). - MOCA defines some fundamental concepts: - Place, Zone, and Beacon - Trigger and Action - Visit [block:image] { "images": [ { "image": [ "https://files.readme.io/WLyeYphSEG6RZQzRWIvs_Da-proximity-experience.png", "Da-proximity-experience.png", "911", "457", "#3ba0da", "" ], "caption": "MOCA Fundamental concepts" } ] } [/block] To start using** Beacon-based proximity experiences** in your Android app, you’ll need to enable proximity service. - Ensure proximity service is enabled in `AndroidManifest.xml file [block:code] { "codes": [ { "code": " <application …>\n\n\t<meta-data android:name=”moca.PROXIMITY_SERVICE_ENABLED\" android:value=\"true\"/>\n", "language": "xml" } ] } [/block] - The MOCA.initializeSDK() call, will automatically start MOCA proximity engine and synchronize proximity campaigns defined in your MOCA cloud account. ###Places Represents a real-world location, such as a store, venue, museum, building, office and so on. - A place can be localized by a geo-fence (GPS location and radius in meters) - A place contains a collection of zones, where each zone defines semantics for an indoor location, such as Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. ###Zone Represents a indoor area or micro-location within the place with user-defined semantics. - Examples include Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. - A zone is defined by a range of one or more beacon sensors. ###Beacon It is a BLE, iBeacon-compatible proximity sensor. - Each beacon is identified by { Proximity UUID, Major and Minor } tuple. - MOCA SDK works with any iBeacon-compatible devices. - This includes MOCA Beacons - And beacons provided by other manufacturers such as Kontakt.io, Estimote, etc. - Beacons are assigned to Zones that define their micro-location semantics. - Each beacon must be registered in MOCA Management Console. ###Campaigns Collections of proximity experiences that are delivered to a user within a specified time frame. ###Experience Defines a proximity interaction with a user. - An experience is composed of a trigger condition and an action. - When proximity trigger conditions are met, the corresponding action is fired. ###Trigger It is a condition or a collection of conditions that must be met to fire an action associated with an experience. For example: - Enter place, - Exit place, - Enter zone, - Exit zone, - Enter beacon range with given proximity, - Exit beacon range, - Custom trigger (implemented as app-provided delegate callback) ###Action Describes an activity to be performed when experience trigger conditions are met. The SDK supports the following actions: - Show local push notification with a specific message - Play sound with a specific file name (included in app bundle) - Play video from URL - Show image from URL - Show HTML content from URL - Open custom URL - Show PassBook card - Custom action (implemented as app-provided delegate callback)
##Introduction - The *MOCA SDK* lets you effortlessly add Bluetooth beacon based proximity experiences to your Android app. - The SDK comes with a powerful proximity engine based on Complex Event Processing logic (see CEP). - MOCA defines some fundamental concepts: - Place, Zone, and Beacon - Trigger and Action - Visit [block:image] { "images": [ { "image": [ "https://files.readme.io/WLyeYphSEG6RZQzRWIvs_Da-proximity-experience.png", "Da-proximity-experience.png", "911", "457", "#3ba0da", "" ], "caption": "MOCA Fundamental concepts" } ] } [/block] To start using** Beacon-based proximity experiences** in your Android app, you’ll need to enable proximity service. - Ensure proximity service is enabled in `AndroidManifest.xml file [block:code] { "codes": [ { "code": " <application …>\n\n\t<meta-data android:name=”moca.PROXIMITY_SERVICE_ENABLED\" android:value=\"true\"/>\n", "language": "xml" } ] } [/block] - The MOCA.initializeSDK() call, will automatically start MOCA proximity engine and synchronize proximity campaigns defined in your MOCA cloud account. ###Places Represents a real-world location, such as a store, venue, museum, building, office and so on. - A place can be localized by a geo-fence (GPS location and radius in meters) - A place contains a collection of zones, where each zone defines semantics for an indoor location, such as Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. ###Zone Represents a indoor area or micro-location within the place with user-defined semantics. - Examples include Kids Clothes, Women Clothes, Entrance, Exit, Books, Videogames, etc. - A zone is defined by a range of one or more beacon sensors. ###Beacon It is a BLE, iBeacon-compatible proximity sensor. - Each beacon is identified by { Proximity UUID, Major and Minor } tuple. - MOCA SDK works with any iBeacon-compatible devices. - This includes MOCA Beacons - And beacons provided by other manufacturers such as Kontakt.io, Estimote, etc. - Beacons are assigned to Zones that define their micro-location semantics. - Each beacon must be registered in MOCA Management Console. ###Campaigns Collections of proximity experiences that are delivered to a user within a specified time frame. ###Experience Defines a proximity interaction with a user. - An experience is composed of a trigger condition and an action. - When proximity trigger conditions are met, the corresponding action is fired. ###Trigger It is a condition or a collection of conditions that must be met to fire an action associated with an experience. For example: - Enter place, - Exit place, - Enter zone, - Exit zone, - Enter beacon range with given proximity, - Exit beacon range, - Custom trigger (implemented as app-provided delegate callback) ###Action Describes an activity to be performed when experience trigger conditions are met. The SDK supports the following actions: - Show local push notification with a specific message - Play sound with a specific file name (included in app bundle) - Play video from URL - Show image from URL - Show HTML content from URL - Open custom URL - Show PassBook card - Custom action (implemented as app-provided delegate callback)
{"_id":"59198f26eba9ac310001865f","body":"You may implement MOCAProximityService.EventListener to handle proximity events:\n\n1 - Add the listener class to MOCA:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAProximityService proxService = MOCA.getProximityService();\\nif (proxService != null) {\\n  proxService.setEventListener(this);\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n2 - Implement the methods.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n* This listener defines the callback methods to respond to\\n* proximity-related events.\\n*/  \\npublic interface EventListener {\\n  public void didEnterRange(MOCABeacon beacon, MOCAProximity proximity);\\n  public void didExitRange(MOCABeacon beacon);\\n  public void didBeaconProximityChange(MOCABeacon beacon, MOCAProximity prevProximity, MOCAProximity curProximity);\\n  public void didEnterPlace(MOCAPlace place);\\n  public void didExitPlace(MOCAPlace place);\\n  public void didEnterZone(MOCAZone zone);\\n  public void didExitZone(MOCAZone zone);\\n  public boolean handleCustomTrigger(String customAttribute);\\n  public void didLoadedBeaconsData(List<MOCABeacon> beacons);        \\n} \\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Important\",\n  \"body\": \"Please note that implementing this interface is **completely optional** , MOCA SDK will take care of detecting beacons, geofences and showing experiences on top of your App UI without having to implement this interface. Use this methods if you want to create custom behaviors inside your application.\",\n  \"sidebar\": true\n}\n[/block]","link_external":false,"link_url":"","next":{"pages":[],"description":""},"order":7,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required","params":[],"url":""},"githubsync":"","isReference":false,"title":"Proximity Events Listener","version":"59198f1eeba9ac31000185de","__v":0,"createdAt":"2015-07-17T17:50:00.964Z","parentDoc":null,"sync_unique":"","updates":[],"user":"559a618bdbcfd20d00710b38","category":"59198f20eba9ac31000185e3","excerpt":"","hidden":false,"project":"559a61d2dbcfd20d00710b39","slug":"proximity-events-listener","type":"basic","childrenPages":[]}

Proximity Events Listener


You may implement MOCAProximityService.EventListener to handle proximity events: 1 - Add the listener class to MOCA: [block:code] { "codes": [ { "code": "MOCAProximityService proxService = MOCA.getProximityService();\nif (proxService != null) {\n proxService.setEventListener(this);\n}", "language": "java" } ] } [/block] 2 - Implement the methods. [block:code] { "codes": [ { "code": "/**\n* This listener defines the callback methods to respond to\n* proximity-related events.\n*/ \npublic interface EventListener {\n public void didEnterRange(MOCABeacon beacon, MOCAProximity proximity);\n public void didExitRange(MOCABeacon beacon);\n public void didBeaconProximityChange(MOCABeacon beacon, MOCAProximity prevProximity, MOCAProximity curProximity);\n public void didEnterPlace(MOCAPlace place);\n public void didExitPlace(MOCAPlace place);\n public void didEnterZone(MOCAZone zone);\n public void didExitZone(MOCAZone zone);\n public boolean handleCustomTrigger(String customAttribute);\n public void didLoadedBeaconsData(List<MOCABeacon> beacons); \n} \n", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "title": "Important", "body": "Please note that implementing this interface is **completely optional** , MOCA SDK will take care of detecting beacons, geofences and showing experiences on top of your App UI without having to implement this interface. Use this methods if you want to create custom behaviors inside your application.", "sidebar": true } [/block]
You may implement MOCAProximityService.EventListener to handle proximity events: 1 - Add the listener class to MOCA: [block:code] { "codes": [ { "code": "MOCAProximityService proxService = MOCA.getProximityService();\nif (proxService != null) {\n proxService.setEventListener(this);\n}", "language": "java" } ] } [/block] 2 - Implement the methods. [block:code] { "codes": [ { "code": "/**\n* This listener defines the callback methods to respond to\n* proximity-related events.\n*/ \npublic interface EventListener {\n public void didEnterRange(MOCABeacon beacon, MOCAProximity proximity);\n public void didExitRange(MOCABeacon beacon);\n public void didBeaconProximityChange(MOCABeacon beacon, MOCAProximity prevProximity, MOCAProximity curProximity);\n public void didEnterPlace(MOCAPlace place);\n public void didExitPlace(MOCAPlace place);\n public void didEnterZone(MOCAZone zone);\n public void didExitZone(MOCAZone zone);\n public boolean handleCustomTrigger(String customAttribute);\n public void didLoadedBeaconsData(List<MOCABeacon> beacons); \n} \n", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "title": "Important", "body": "Please note that implementing this interface is **completely optional** , MOCA SDK will take care of detecting beacons, geofences and showing experiences on top of your App UI without having to implement this interface. Use this methods if you want to create custom behaviors inside your application.", "sidebar": true } [/block]
{"_id":"59198f26eba9ac3100018660","category":"59198f20eba9ac31000185e3","createdAt":"2015-07-17T17:51:20.498Z","excerpt":"","isReference":false,"order":8,"type":"basic","user":"559a618bdbcfd20d00710b38","api":{"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[]},"version":"59198f1eeba9ac31000185de","body":"You may also customize actions using `MOCAProximityService.ActionListener`:\n\n1 - Add the listener to MOCA:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"MOCAProximityService proxService = MOCA.getProximityService();\\nif (proxService != null) {\\n\\tproxService.setActionListener(this);\\n}\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Important\",\n  \"body\": \"If you implement this interface within an Activity, your actions won't be always executed in background. If you **always** want to listen to this actions, even in background, ensure you implement this in a class that inherits from **Application** (the same where you initialize MOCA SDK).\"\n}\n[/block]\n1 - Implement the methods:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**       \\n* This listener defines the callback methods to respond to       \\n* proximity-invoked actions.       \\n*/      \\npublic interface ActionListener {\\n\\n   boolean displayNotificationAlert(String alertMessage);\\n   boolean openUrl(URL url);   \\n   boolean showHtmlWithString (String html);   \\n   boolean playVideoFromUrl(URL url);   \\n   boolean displayImageFromUrl(URL url); \\n   boolean displayPassFromUrl(URL url);  \\n   boolean addTag(String tagName, String value);\\n   boolean playNotificationSound(String soundFilename);\\n//return true if you want to track this action in MOCA Campaign Analytics\\n   boolean performCustomAction(String customAttribute);         \\n\\n}\\n \\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"body\": \"By implementing this interface, you will be notified when an experience is about to be shown to the user. If the method returns `true`, MOCA assumes you have completely handled the behavior, so **no further action will be performed**. Return `false` if you want to be notified about the experience, but still want MOCA to execute the default behavior.\",\n  \"title\": \"\",\n  \"sidebar\": true\n}\n[/block]","githubsync":"","sync_unique":"","__v":0,"link_external":false,"next":{"pages":[],"description":""},"parentDoc":null,"title":"Proximity Actions Listener","updates":[],"hidden":false,"link_url":"","project":"559a61d2dbcfd20d00710b39","slug":"proximity-actions-listener","childrenPages":[]}

Proximity Actions Listener


You may also customize actions using `MOCAProximityService.ActionListener`: 1 - Add the listener to MOCA: [block:code] { "codes": [ { "code": "MOCAProximityService proxService = MOCA.getProximityService();\nif (proxService != null) {\n\tproxService.setActionListener(this);\n}", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "title": "Important", "body": "If you implement this interface within an Activity, your actions won't be always executed in background. If you **always** want to listen to this actions, even in background, ensure you implement this in a class that inherits from **Application** (the same where you initialize MOCA SDK)." } [/block] 1 - Implement the methods: [block:code] { "codes": [ { "code": "/** \n* This listener defines the callback methods to respond to \n* proximity-invoked actions. \n*/ \npublic interface ActionListener {\n\n boolean displayNotificationAlert(String alertMessage);\n boolean openUrl(URL url); \n boolean showHtmlWithString (String html); \n boolean playVideoFromUrl(URL url); \n boolean displayImageFromUrl(URL url); \n boolean displayPassFromUrl(URL url); \n boolean addTag(String tagName, String value);\n boolean playNotificationSound(String soundFilename);\n//return true if you want to track this action in MOCA Campaign Analytics\n boolean performCustomAction(String customAttribute);  \n\n}\n \n", "language": "java" } ] } [/block] [block:callout] { "type": "danger", "body": "By implementing this interface, you will be notified when an experience is about to be shown to the user. If the method returns `true`, MOCA assumes you have completely handled the behavior, so **no further action will be performed**. Return `false` if you want to be notified about the experience, but still want MOCA to execute the default behavior.", "title": "", "sidebar": true } [/block]
You may also customize actions using `MOCAProximityService.ActionListener`: 1 - Add the listener to MOCA: [block:code] { "codes": [ { "code": "MOCAProximityService proxService = MOCA.getProximityService();\nif (proxService != null) {\n\tproxService.setActionListener(this);\n}", "language": "java" } ] } [/block] [block:callout] { "type": "warning", "title": "Important", "body": "If you implement this interface within an Activity, your actions won't be always executed in background. If you **always** want to listen to this actions, even in background, ensure you implement this in a class that inherits from **Application** (the same where you initialize MOCA SDK)." } [/block] 1 - Implement the methods: [block:code] { "codes": [ { "code": "/** \n* This listener defines the callback methods to respond to \n* proximity-invoked actions. \n*/ \npublic interface ActionListener {\n\n boolean displayNotificationAlert(String alertMessage);\n boolean openUrl(URL url); \n boolean showHtmlWithString (String html); \n boolean playVideoFromUrl(URL url); \n boolean displayImageFromUrl(URL url); \n boolean displayPassFromUrl(URL url); \n boolean addTag(String tagName, String value);\n boolean playNotificationSound(String soundFilename);\n//return true if you want to track this action in MOCA Campaign Analytics\n boolean performCustomAction(String customAttribute);  \n\n}\n \n", "language": "java" } ] } [/block] [block:callout] { "type": "danger", "body": "By implementing this interface, you will be notified when an experience is about to be shown to the user. If the method returns `true`, MOCA assumes you have completely handled the behavior, so **no further action will be performed**. Return `false` if you want to be notified about the experience, but still want MOCA to execute the default behavior.", "title": "", "sidebar": true } [/block]
{"_id":"59198f26eba9ac3100018661","next":{"pages":[],"description":""},"parentDoc":null,"sync_unique":"","version":"59198f1eeba9ac31000185de","api":{"params":[],"url":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":"","auth":"required"},"link_external":false,"body":"##Location service authorization\n- By default, MOCA tracks user location and proximity interactions\n- The geo-location is tracked with 100-meter precision. \n- This is performed by means of Google Play Services Locations API\n- The user must allow the location tracking for the device\n- The geo-location minimizes battery usage by employing adaptive tracking\n- When the permission is not granted, MOCA does not track user location.\n\n##How event tracking works\n- MOCA SDK uses SQLite database stored in a local file on your phone to store all locally tracked events.\n- Periodically, when your device is connected to Internet (via Edge, 3G, LTE or Wifi), \u000bthe SDK incrementally transfers the packs of events to the cloud.\n- The local database is freed only when the transfer is successful (Store-And-Forward)\n- By default, the event transfer is performed every 15 minutes\n\n##Offline behavior\n- MOCA SDK downloads proximity campaigns data from the cloud asynchronously using \u000bperiodic asynchronous background fetch mechanism. \n- The frequency is controlled by SDK but can also be tuned by the app.\n- The downloaded data is persisted locally and acts as a cache.\n- If the connection to Internet is not available, the cached data is used to run the campaigns.\n- This enables you to offer proximity experiences even if the Internet connection is saturated or not available.","excerpt":"","slug":"design-considerations-1","__v":0,"link_url":"","project":"559a61d2dbcfd20d00710b39","type":"basic","user":"559a618bdbcfd20d00710b38","category":"59198f20eba9ac31000185e3","hidden":false,"isReference":false,"order":9,"title":"Design considerations","updates":[],"createdAt":"2015-07-17T17:53:16.944Z","githubsync":"","childrenPages":[]}

Design considerations


##Location service authorization - By default, MOCA tracks user location and proximity interactions - The geo-location is tracked with 100-meter precision. - This is performed by means of Google Play Services Locations API - The user must allow the location tracking for the device - The geo-location minimizes battery usage by employing adaptive tracking - When the permission is not granted, MOCA does not track user location. ##How event tracking works - MOCA SDK uses SQLite database stored in a local file on your phone to store all locally tracked events. - Periodically, when your device is connected to Internet (via Edge, 3G, LTE or Wifi), the SDK incrementally transfers the packs of events to the cloud. - The local database is freed only when the transfer is successful (Store-And-Forward) - By default, the event transfer is performed every 15 minutes ##Offline behavior - MOCA SDK downloads proximity campaigns data from the cloud asynchronously using periodic asynchronous background fetch mechanism. - The frequency is controlled by SDK but can also be tuned by the app. - The downloaded data is persisted locally and acts as a cache. - If the connection to Internet is not available, the cached data is used to run the campaigns. - This enables you to offer proximity experiences even if the Internet connection is saturated or not available.
##Location service authorization - By default, MOCA tracks user location and proximity interactions - The geo-location is tracked with 100-meter precision. - This is performed by means of Google Play Services Locations API - The user must allow the location tracking for the device - The geo-location minimizes battery usage by employing adaptive tracking - When the permission is not granted, MOCA does not track user location. ##How event tracking works - MOCA SDK uses SQLite database stored in a local file on your phone to store all locally tracked events. - Periodically, when your device is connected to Internet (via Edge, 3G, LTE or Wifi), the SDK incrementally transfers the packs of events to the cloud. - The local database is freed only when the transfer is successful (Store-And-Forward) - By default, the event transfer is performed every 15 minutes ##Offline behavior - MOCA SDK downloads proximity campaigns data from the cloud asynchronously using periodic asynchronous background fetch mechanism. - The frequency is controlled by SDK but can also be tuned by the app. - The downloaded data is persisted locally and acts as a cache. - If the connection to Internet is not available, the cached data is used to run the campaigns. - This enables you to offer proximity experiences even if the Internet connection is saturated or not available.
{"_id":"5990853c5af2a900234df84c","project":"559a61d2dbcfd20d00710b39","version":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e3","user":"559a618bdbcfd20d00710b38","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-08-13T16:58:36.801Z","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":999,"body":"Through the MOCA Indoor Location API, mobile applications are able get their current location indoors with GPS-grade accuracy.\nLocation is provided by using and combining signals from a variety of sensors, including Bluetooth, Wi-Fi or Microelectromechanical systems (Gyroscope, Compass, and Accelerometer).\n\nMOCA SDK relies on PoleStar NAO™ SDK  to calculate this indoor location data. \n\nNAO is a trademark from PoleStar SA. Learn more about PoleStar solutions at [http://www.polestar.eu/](http://www.polestar.eu/)\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"body\": \"You will need an account with PoleStar in order to use this feature.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Additional integration steps for NAO SDK\"\n}\n[/block]\nAlong with the MOCA SDK dependency, add the latest version of the NAO SDK in your dependencies list.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"compile 'eu.polestar:naosdk:4.+' // final '+' ensures you are using the latest version in the 4.0 series\",\n      \"language\": \"groovy\"\n    }\n  ]\n}\n[/block]\nAll receivers and services are already declared in the MOCA SDK, so there is no need to re declare it in your AndroidManifest.xml file.\n\n##Settings in MOCA.properties file\n\nThe NAO SDK has to be explicitly activated in the `MOCA.properties` file. Add the following key:\n\n`moca.CUSTOM_NAOMICRO_ENABLED = true`\n\nOn the other hand, it is strongly recommended that you disable the MOCA beacon location engine, otherwise the power consumption of the application will be dramatically high. In order to deactivate the MOCA Beacon engine, add / modify the following parameter\n\n`mocaDriver = false`\n\nEnsure that both `proximity` and `geotracking` are turned on in the config.\n[block:api-header]\n{\n  \"title\": \"NAO API Key configuration\"\n}\n[/block]\nBefore starting to integrate the code, you will need to add a NAO API Key to the Indoor-Enabled place in your MOCA Console.\n\nNOTE: Currently there is no UI to add this key to the MOCA Place. Please send us a message to support@mocaplatform.com with your NAO API Key, the account where you want to add the Key, and the Place name or place ID\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Emulator key\",\n  \"body\": \"NAO allows the usage of an \\\"emulator\\\" key, very useful during the integration step. Please create a place and a geofence around where you physically are developing the application and let us know what that place is, so we can add an emulator key that will work in the development enviroment.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"MOCA Indoor Location interface\"\n}\n[/block]\nOnce you have configured the SDK. You are now ready to use the Indoor Location API.\n\n##Creating an Indoor Location Client\n\nUse the following method to request a new client:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"public static MOCAIndoorClient createIndoorClient (@NonNull final MOCAIndoorClient.Listener listener);\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nThe MOCAIndoorClient.Listener interface allows you to receive callbacks when there is a new location available (Boxed within an Android standard `Location` object), an initialization error, or a system warning:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"public interface MOCAIndoorClient.Listener {\\n   \\t/**\\n         * Tells the listener that new location data is available.\\n         * @param location\\n         */\\n        void onLocationChanged(Location location);\\n\\n        /**\\n         * Tells the listener that the location client was unable to retrieve a location value.\\n         * @param errorCode - error code\\n         * @param errorMessage - description of the error\\n         */\\n        void onError(Error errorCode, String errorMessage);\\n\\n        /**\\n         * Tells the listener that a temporary problem has occurred. It might be necessary the app\\n         * takes actions to resolve some of the problems. Please review the warnings for specific\\n         * description.\\n         *\\n         * @param warningCode\\n         * @param warningMessage\\n         */\\n        void onWarning(Warning warningCode, String warningMessage);\\n\\n        /**\\n         * Tells the listener that the synchronization with the cloud has successfully finished.\\n         */\\n        void onSyncCompleted();\\n}\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nThis is the description of the possible Warnings and Errors\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/**\\n* Indoor location client errors\\n*/\\nenum Error {\\n   /**\\n    * Notified when the indoor location service error occurred. Please refer\\n    * to error message for details.\\n    */\\n   GENERIC_ERROR,\\n   /**\\n    * Notified when MOCAPlace configuration is invalid for the indoor location service.\\n    * This is fatal error. Please refer to error message for details.\\n    */\\n   INVALID_PLACE_CONFIGURATION,\\n   /**\\n    * Notified when the indoor location service is not supported on device OS.\\n    */\\n   UNSUPPORTED_OS\\n}\\n\\n     /**\\n     * Indoor location client warnings\\n     */\\n    enum Warning {\\n        /**\\n         * Notified when the device is outside the indoor-enabled MOCAPlace.\\n         */\\n        LOCATION_TEMPORARY_UNAVAILABLE,\\n        /**\\n         * Notified when the synchronization with the cloud has failed.\\n         */\\n        SYNC_ERROR,\\n        /**\\n         * Notified when Location Services is not enabled on Android device.\\n         * The app should advice the user to turn Location Services on to enable indoor location.\\n         */\\n        LOCATION_SERVICES_NOT_ENABLED,\\n        /**\\n         * Notified when user did not granted Location Permissions for the app.\\n         * The app should advice the user to opt-in for Location Services.\\n         * @see <a href=\\\"http://developer.mocaplatform.com/docs/android-60-permissions\\\">MOCA Android Permissions</a>\\n         */\\n        LOCATION_PERMISSION_NOT_GRANTED,\\n        /**\\n         * Notified when Bluetooth is not enabled and is required by the location service.\\n         * The app should advice the user to turn Bluetooth on to enable indoor location.\\n         */\\n        BLE_NOT_ENABLED,\\n        /**\\n         * Notified when Wi-Fi is not enabled and is required by the location service.\\n         * The app should advice the user to turn Wi-Fi on to enable indoor location.\\n         */\\n        WIFI_NOT_ENABLED,\\n        /**\\n         * Notified when a compass calibration is needed for the client to work properly.\\n         */\\n        REQUIRES_COMPASS_CALIBRATION,\\n        /**\\n         * No Positioning Database (PDB) is available. You may place static PDB in assets/pdbs folder\\n         * or use sync() call on MOCAIndoorClient to download it from cloud.\\n         */\\n        NO_POSITIONING_DATABASE\\n    }\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nSome of these warnings could be solved by requesting to the user an action. For example if bluetooth is not turned on, handle the warning by showing a popup asking to switch on BLE. Is up to you to decide whether the user should see a message or not.\n\nThe Indoor Location Engine will return location data once every ~second, you will need to connect the map with the engine in the onLocationChanged method.\n\nPlease `stop` / `close` the client when the Map Activity is no longer visible / destroyed. This is important to avoid unnecessary `power consumption.`\nCheck the code sample below:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    @Override\\n    public void onStop(){\\n        super.onStop();\\n\\n        if(indoorClient != null){\\n            indoorClient.stop();\\n        }\\n    }\\n\\n    @Override\\n    public void onDestroy(){\\n        super.onDestroy();\\n        if(indoorClient != null) {\\n            indoorClient.close();\\n        }\\n    }\\n\\n\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\nResume the location when the map activity is visible again:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    @Override\\n    public void onResume(){\\n        super.onResume();\\n        if(indoorClient != null){\\n            indoorClient.start();\\n        }\\n    }\",\n      \"language\": \"java\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Errors and Warnings\"\n}\n[/block]\n`Errors:`\n\n**GENERIC_ERROR**\nThere was something wrong with the location engine, check the error message for more information.\n\n**INVALID_PLACE_CONFIGURATION**\nInvalid API key : inconsistent key across services or key does not match PDB: check for typo in your key, check your site details on MOCA Console or contact Support.\n\n**UNSUPPORTED_OS**\nUnsupported OS\n\n`Warnings:`\n\n**LOCATION_TEMPORARY_UNAVAILABLE**\nLocation is unavailable as device is off-site.\n\n**SYNC_ERROR**\nThere was an error while syncing data. Check there is internet connection / PDB is published in the nao cloud.\n\n**LOCATION_SERVICES_NOT_ENABLED**\nUser has disabled location services on the Android Device.\n\n**LOCATION_PERMISSION_NOT_GRANTED**\nUser denied location permission, engine cannot start without this permission.\n\n**BLE_NOT_ENABLED**\nBluetooth Low Energy is not turned on. This radio is needed for indoor positioning.\n\n**WIFI_NOT_ENABLED**\nWiFi is not turned on and service requires it in order to work,\n\n**REQUIRES_COMPASS_CALIBRATION**\nCompass not calibrated, user needs to recalibrate it.\n\n**NO_POSITIONING_DATABASE**\nNo Positioning Database (PDB) is available. You may place static PDB in assets/pdbs folder or use sync() call on MOCAIndoorClient to download it from cloud.","excerpt":"","slug":"indoor-location-api-1","type":"basic","title":"Indoor Location API","__v":0,"childrenPages":[]}

Indoor Location API


Through the MOCA Indoor Location API, mobile applications are able get their current location indoors with GPS-grade accuracy. Location is provided by using and combining signals from a variety of sensors, including Bluetooth, Wi-Fi or Microelectromechanical systems (Gyroscope, Compass, and Accelerometer). MOCA SDK relies on PoleStar NAO™ SDK to calculate this indoor location data. NAO is a trademark from PoleStar SA. Learn more about PoleStar solutions at [http://www.polestar.eu/](http://www.polestar.eu/) [block:callout] { "type": "danger", "body": "You will need an account with PoleStar in order to use this feature." } [/block] [block:api-header] { "title": "Additional integration steps for NAO SDK" } [/block] Along with the MOCA SDK dependency, add the latest version of the NAO SDK in your dependencies list. [block:code] { "codes": [ { "code": "compile 'eu.polestar:naosdk:4.+' // final '+' ensures you are using the latest version in the 4.0 series", "language": "groovy" } ] } [/block] All receivers and services are already declared in the MOCA SDK, so there is no need to re declare it in your AndroidManifest.xml file. ##Settings in MOCA.properties file The NAO SDK has to be explicitly activated in the `MOCA.properties` file. Add the following key: `moca.CUSTOM_NAOMICRO_ENABLED = true` On the other hand, it is strongly recommended that you disable the MOCA beacon location engine, otherwise the power consumption of the application will be dramatically high. In order to deactivate the MOCA Beacon engine, add / modify the following parameter `mocaDriver = false` Ensure that both `proximity` and `geotracking` are turned on in the config. [block:api-header] { "title": "NAO API Key configuration" } [/block] Before starting to integrate the code, you will need to add a NAO API Key to the Indoor-Enabled place in your MOCA Console. NOTE: Currently there is no UI to add this key to the MOCA Place. Please send us a message to support@mocaplatform.com with your NAO API Key, the account where you want to add the Key, and the Place name or place ID [block:callout] { "type": "info", "title": "Emulator key", "body": "NAO allows the usage of an \"emulator\" key, very useful during the integration step. Please create a place and a geofence around where you physically are developing the application and let us know what that place is, so we can add an emulator key that will work in the development enviroment." } [/block] [block:api-header] { "title": "MOCA Indoor Location interface" } [/block] Once you have configured the SDK. You are now ready to use the Indoor Location API. ##Creating an Indoor Location Client Use the following method to request a new client: [block:code] { "codes": [ { "code": "public static MOCAIndoorClient createIndoorClient (@NonNull final MOCAIndoorClient.Listener listener);", "language": "java" } ] } [/block] The MOCAIndoorClient.Listener interface allows you to receive callbacks when there is a new location available (Boxed within an Android standard `Location` object), an initialization error, or a system warning: [block:code] { "codes": [ { "code": "public interface MOCAIndoorClient.Listener {\n \t/**\n * Tells the listener that new location data is available.\n * @param location\n */\n void onLocationChanged(Location location);\n\n /**\n * Tells the listener that the location client was unable to retrieve a location value.\n * @param errorCode - error code\n * @param errorMessage - description of the error\n */\n void onError(Error errorCode, String errorMessage);\n\n /**\n * Tells the listener that a temporary problem has occurred. It might be necessary the app\n * takes actions to resolve some of the problems. Please review the warnings for specific\n * description.\n *\n * @param warningCode\n * @param warningMessage\n */\n void onWarning(Warning warningCode, String warningMessage);\n\n /**\n * Tells the listener that the synchronization with the cloud has successfully finished.\n */\n void onSyncCompleted();\n}\n", "language": "java" } ] } [/block] This is the description of the possible Warnings and Errors [block:code] { "codes": [ { "code": "/**\n* Indoor location client errors\n*/\nenum Error {\n /**\n * Notified when the indoor location service error occurred. Please refer\n * to error message for details.\n */\n GENERIC_ERROR,\n /**\n * Notified when MOCAPlace configuration is invalid for the indoor location service.\n * This is fatal error. Please refer to error message for details.\n */\n INVALID_PLACE_CONFIGURATION,\n /**\n * Notified when the indoor location service is not supported on device OS.\n */\n UNSUPPORTED_OS\n}\n\n /**\n * Indoor location client warnings\n */\n enum Warning {\n /**\n * Notified when the device is outside the indoor-enabled MOCAPlace.\n */\n LOCATION_TEMPORARY_UNAVAILABLE,\n /**\n * Notified when the synchronization with the cloud has failed.\n */\n SYNC_ERROR,\n /**\n * Notified when Location Services is not enabled on Android device.\n * The app should advice the user to turn Location Services on to enable indoor location.\n */\n LOCATION_SERVICES_NOT_ENABLED,\n /**\n * Notified when user did not granted Location Permissions for the app.\n * The app should advice the user to opt-in for Location Services.\n * @see <a href=\"http://developer.mocaplatform.com/docs/android-60-permissions\">MOCA Android Permissions</a>\n */\n LOCATION_PERMISSION_NOT_GRANTED,\n /**\n * Notified when Bluetooth is not enabled and is required by the location service.\n * The app should advice the user to turn Bluetooth on to enable indoor location.\n */\n BLE_NOT_ENABLED,\n /**\n * Notified when Wi-Fi is not enabled and is required by the location service.\n * The app should advice the user to turn Wi-Fi on to enable indoor location.\n */\n WIFI_NOT_ENABLED,\n /**\n * Notified when a compass calibration is needed for the client to work properly.\n */\n REQUIRES_COMPASS_CALIBRATION,\n /**\n * No Positioning Database (PDB) is available. You may place static PDB in assets/pdbs folder\n * or use sync() call on MOCAIndoorClient to download it from cloud.\n */\n NO_POSITIONING_DATABASE\n }\n", "language": "java" } ] } [/block] Some of these warnings could be solved by requesting to the user an action. For example if bluetooth is not turned on, handle the warning by showing a popup asking to switch on BLE. Is up to you to decide whether the user should see a message or not. The Indoor Location Engine will return location data once every ~second, you will need to connect the map with the engine in the onLocationChanged method. Please `stop` / `close` the client when the Map Activity is no longer visible / destroyed. This is important to avoid unnecessary `power consumption.` Check the code sample below: [block:code] { "codes": [ { "code": " @Override\n public void onStop(){\n super.onStop();\n\n if(indoorClient != null){\n indoorClient.stop();\n }\n }\n\n @Override\n public void onDestroy(){\n super.onDestroy();\n if(indoorClient != null) {\n indoorClient.close();\n }\n }\n\n", "language": "java" } ] } [/block] Resume the location when the map activity is visible again: [block:code] { "codes": [ { "code": " @Override\n public void onResume(){\n super.onResume();\n if(indoorClient != null){\n indoorClient.start();\n }\n }", "language": "java" } ] } [/block] [block:api-header] { "title": "Errors and Warnings" } [/block] `Errors:` **GENERIC_ERROR** There was something wrong with the location engine, check the error message for more information. **INVALID_PLACE_CONFIGURATION** Invalid API key : inconsistent key across services or key does not match PDB: check for typo in your key, check your site details on MOCA Console or contact Support. **UNSUPPORTED_OS** Unsupported OS `Warnings:` **LOCATION_TEMPORARY_UNAVAILABLE** Location is unavailable as device is off-site. **SYNC_ERROR** There was an error while syncing data. Check there is internet connection / PDB is published in the nao cloud. **LOCATION_SERVICES_NOT_ENABLED** User has disabled location services on the Android Device. **LOCATION_PERMISSION_NOT_GRANTED** User denied location permission, engine cannot start without this permission. **BLE_NOT_ENABLED** Bluetooth Low Energy is not turned on. This radio is needed for indoor positioning. **WIFI_NOT_ENABLED** WiFi is not turned on and service requires it in order to work, **REQUIRES_COMPASS_CALIBRATION** Compass not calibrated, user needs to recalibrate it. **NO_POSITIONING_DATABASE** No Positioning Database (PDB) is available. You may place static PDB in assets/pdbs folder or use sync() call on MOCAIndoorClient to download it from cloud.
Through the MOCA Indoor Location API, mobile applications are able get their current location indoors with GPS-grade accuracy. Location is provided by using and combining signals from a variety of sensors, including Bluetooth, Wi-Fi or Microelectromechanical systems (Gyroscope, Compass, and Accelerometer). MOCA SDK relies on PoleStar NAO™ SDK to calculate this indoor location data. NAO is a trademark from PoleStar SA. Learn more about PoleStar solutions at [http://www.polestar.eu/](http://www.polestar.eu/) [block:callout] { "type": "danger", "body": "You will need an account with PoleStar in order to use this feature." } [/block] [block:api-header] { "title": "Additional integration steps for NAO SDK" } [/block] Along with the MOCA SDK dependency, add the latest version of the NAO SDK in your dependencies list. [block:code] { "codes": [ { "code": "compile 'eu.polestar:naosdk:4.+' // final '+' ensures you are using the latest version in the 4.0 series", "language": "groovy" } ] } [/block] All receivers and services are already declared in the MOCA SDK, so there is no need to re declare it in your AndroidManifest.xml file. ##Settings in MOCA.properties file The NAO SDK has to be explicitly activated in the `MOCA.properties` file. Add the following key: `moca.CUSTOM_NAOMICRO_ENABLED = true` On the other hand, it is strongly recommended that you disable the MOCA beacon location engine, otherwise the power consumption of the application will be dramatically high. In order to deactivate the MOCA Beacon engine, add / modify the following parameter `mocaDriver = false` Ensure that both `proximity` and `geotracking` are turned on in the config. [block:api-header] { "title": "NAO API Key configuration" } [/block] Before starting to integrate the code, you will need to add a NAO API Key to the Indoor-Enabled place in your MOCA Console. NOTE: Currently there is no UI to add this key to the MOCA Place. Please send us a message to support@mocaplatform.com with your NAO API Key, the account where you want to add the Key, and the Place name or place ID [block:callout] { "type": "info", "title": "Emulator key", "body": "NAO allows the usage of an \"emulator\" key, very useful during the integration step. Please create a place and a geofence around where you physically are developing the application and let us know what that place is, so we can add an emulator key that will work in the development enviroment." } [/block] [block:api-header] { "title": "MOCA Indoor Location interface" } [/block] Once you have configured the SDK. You are now ready to use the Indoor Location API. ##Creating an Indoor Location Client Use the following method to request a new client: [block:code] { "codes": [ { "code": "public static MOCAIndoorClient createIndoorClient (@NonNull final MOCAIndoorClient.Listener listener);", "language": "java" } ] } [/block] The MOCAIndoorClient.Listener interface allows you to receive callbacks when there is a new location available (Boxed within an Android standard `Location` object), an initialization error, or a system warning: [block:code] { "codes": [ { "code": "public interface MOCAIndoorClient.Listener {\n \t/**\n * Tells the listener that new location data is available.\n * @param location\n */\n void onLocationChanged(Location location);\n\n /**\n * Tells the listener that the location client was unable to retrieve a location value.\n * @param errorCode - error code\n * @param errorMessage - description of the error\n */\n void onError(Error errorCode, String errorMessage);\n\n /**\n * Tells the listener that a temporary problem has occurred. It might be necessary the app\n * takes actions to resolve some of the problems. Please review the warnings for specific\n * description.\n *\n * @param warningCode\n * @param warningMessage\n */\n void onWarning(Warning warningCode, String warningMessage);\n\n /**\n * Tells the listener that the synchronization with the cloud has successfully finished.\n */\n void onSyncCompleted();\n}\n", "language": "java" } ] } [/block] This is the description of the possible Warnings and Errors [block:code] { "codes": [ { "code": "/**\n* Indoor location client errors\n*/\nenum Error {\n /**\n * Notified when the indoor location service error occurred. Please refer\n * to error message for details.\n */\n GENERIC_ERROR,\n /**\n * Notified when MOCAPlace configuration is invalid for the indoor location service.\n * This is fatal error. Please refer to error message for details.\n */\n INVALID_PLACE_CONFIGURATION,\n /**\n * Notified when the indoor location service is not supported on device OS.\n */\n UNSUPPORTED_OS\n}\n\n /**\n * Indoor location client warnings\n */\n enum Warning {\n /**\n * Notified when the device is outside the indoor-enabled MOCAPlace.\n */\n LOCATION_TEMPORARY_UNAVAILABLE,\n /**\n * Notified when the synchronization with the cloud has failed.\n */\n SYNC_ERROR,\n /**\n * Notified when Location Services is not enabled on Android device.\n * The app should advice the user to turn Location Services on to enable indoor location.\n */\n LOCATION_SERVICES_NOT_ENABLED,\n /**\n * Notified when user did not granted Location Permissions for the app.\n * The app should advice the user to opt-in for Location Services.\n * @see <a href=\"http://developer.mocaplatform.com/docs/android-60-permissions\">MOCA Android Permissions</a>\n */\n LOCATION_PERMISSION_NOT_GRANTED,\n /**\n * Notified when Bluetooth is not enabled and is required by the location service.\n * The app should advice the user to turn Bluetooth on to enable indoor location.\n */\n BLE_NOT_ENABLED,\n /**\n * Notified when Wi-Fi is not enabled and is required by the location service.\n * The app should advice the user to turn Wi-Fi on to enable indoor location.\n */\n WIFI_NOT_ENABLED,\n /**\n * Notified when a compass calibration is needed for the client to work properly.\n */\n REQUIRES_COMPASS_CALIBRATION,\n /**\n * No Positioning Database (PDB) is available. You may place static PDB in assets/pdbs folder\n * or use sync() call on MOCAIndoorClient to download it from cloud.\n */\n NO_POSITIONING_DATABASE\n }\n", "language": "java" } ] } [/block] Some of these warnings could be solved by requesting to the user an action. For example if bluetooth is not turned on, handle the warning by showing a popup asking to switch on BLE. Is up to you to decide whether the user should see a message or not. The Indoor Location Engine will return location data once every ~second, you will need to connect the map with the engine in the onLocationChanged method. Please `stop` / `close` the client when the Map Activity is no longer visible / destroyed. This is important to avoid unnecessary `power consumption.` Check the code sample below: [block:code] { "codes": [ { "code": " @Override\n public void onStop(){\n super.onStop();\n\n if(indoorClient != null){\n indoorClient.stop();\n }\n }\n\n @Override\n public void onDestroy(){\n super.onDestroy();\n if(indoorClient != null) {\n indoorClient.close();\n }\n }\n\n", "language": "java" } ] } [/block] Resume the location when the map activity is visible again: [block:code] { "codes": [ { "code": " @Override\n public void onResume(){\n super.onResume();\n if(indoorClient != null){\n indoorClient.start();\n }\n }", "language": "java" } ] } [/block] [block:api-header] { "title": "Errors and Warnings" } [/block] `Errors:` **GENERIC_ERROR** There was something wrong with the location engine, check the error message for more information. **INVALID_PLACE_CONFIGURATION** Invalid API key : inconsistent key across services or key does not match PDB: check for typo in your key, check your site details on MOCA Console or contact Support. **UNSUPPORTED_OS** Unsupported OS `Warnings:` **LOCATION_TEMPORARY_UNAVAILABLE** Location is unavailable as device is off-site. **SYNC_ERROR** There was an error while syncing data. Check there is internet connection / PDB is published in the nao cloud. **LOCATION_SERVICES_NOT_ENABLED** User has disabled location services on the Android Device. **LOCATION_PERMISSION_NOT_GRANTED** User denied location permission, engine cannot start without this permission. **BLE_NOT_ENABLED** Bluetooth Low Energy is not turned on. This radio is needed for indoor positioning. **WIFI_NOT_ENABLED** WiFi is not turned on and service requires it in order to work, **REQUIRES_COMPASS_CALIBRATION** Compass not calibrated, user needs to recalibrate it. **NO_POSITIONING_DATABASE** No Positioning Database (PDB) is available. You may place static PDB in assets/pdbs folder or use sync() call on MOCAIndoorClient to download it from cloud.
{"_id":"59198f23eba9ac310001861c","__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\n  ````\n    cordova platform add android\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=\"15\" />\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":"59198f1eeba9ac31000185de","api":{"auth":"required","params":[],"url":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"status":400,"name":"","code":"{}","language":"json"}]},"settings":""},"category":"59198f20eba9ac31000185e5","link_external":false,"link_url":"","parentDoc":null,"project":"559a61d2dbcfd20d00710b39","user":"559a618bdbcfd20d00710b38","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). ```` cordova platform add android ```` 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="15" /> <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). ```` cordova platform add android ```` 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="15" /> <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":"59198f23eba9ac310001861d","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":"59198f20eba9ac31000185e5","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":"59198f1eeba9ac31000185de","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}]}},"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":"59198f23eba9ac310001861e","next":{"pages":[],"description":""},"slug":"basic-examples","type":"basic","user":"559a618bdbcfd20d00710b38","version":"59198f1eeba9ac31000185de","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":"59198f20eba9ac31000185e5","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","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":"59198f23eba9ac3100018620","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":"59198f20eba9ac31000185e5","createdAt":"2016-07-26T17:26:22.879Z","isReference":false,"next":{"pages":[],"description":""},"slug":"common-issues-troubleshooting","version":"59198f1eeba9ac31000185de","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:support@mocaplatform.com). 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`","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:support@mocaplatform.com). 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:support@mocaplatform.com). 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":"59c912951883c7003aa12619","project":"559a61d2dbcfd20d00710b39","version":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e5","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":999,"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,"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":"59198f22eba9ac310001860e","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 (key, value) {\\n      // ...\\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":"59198f1eeba9ac31000185de","__v":0,"category":"59198f20eba9ac31000185e6","createdAt":"2015-07-31T09:58:36.554Z","next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","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 (key, value) {\n // ...\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 (key, value) {\n // ...\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":"59198f22eba9ac310001860f","hidden":false,"next":{"pages":[],"description":""},"project":"559a61d2dbcfd20d00710b39","slug":"javascript-moca-constants","user":"55a61860249a40190051d941","version":"59198f1eeba9ac31000185de","__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":"59198f20eba9ac31000185e6","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":"59198f22eba9ac3100018610","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":"59198f1eeba9ac31000185de","category":"59198f20eba9ac31000185e6","githubsync":"","parentDoc":null,"title":"JavaScript Trigger Events","updates":[],"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":"59198f22eba9ac3100018611","__v":0,"version":"59198f1eeba9ac31000185de","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":"59198f20eba9ac31000185e6","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","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]