Sunday 25 October 2015

HB Blog 100: How To Draw Graphic Elements On MapView Using ArcGIS Android SDK???

In this post, I will brief little about ArcGIS. ArcGIS is a geographic information system (GIS) for working with maps and geographic information. It is used for: creating and using maps; compiling geographic data; analyzing mapped information; sharing and discovering geographic information; using maps and geographic information in a range of applications; and managing geographic information in a database.

Refer below link for Android setup and documentation for ArcGIS Android SDK.
https://developers.arcgis.com/android/

There are many customization that can be done in maps using ArcGIS, I would like to show how to plot point, polylines, polygone, etc. Basically, ArcGIS is made with different layers such as featured layer, graphic layer, etc.  While drawing or plotting grahpical elements or callout on map we use graphic layer. MapView has two layers (that is, a TiledMapServiceLayer and GraphicsLayer). The TiledMapServiceLayer points to a map service on one of Esri's servers, while the GraphicsLayer holds graphic elements that a user draws on the screen. When the sample application starts, a MapView, TiledMapServiceLayer, and GraphicsLayer are instantiated. A TouchListener is added to a MapView and other Android user interface (UI) elements (AlertDialog, Buttons) are also instantiated.
When a user selects a geometry type from the AlertDialog, the AlertDialog's onClick() handler method assigns the appropriate symbology to the GraphicLayer's renderer. The MapView's TouchListener class has handlers to listen to SingleTap, OnDragPointerMove, and OnDragPointerUp events. These collect geometry based on the user's actions on the screen and assign this geometry to a graphic object, which is then added to the GraphicsLayer. This application also retains its state when the device is flipped or the user switches to another application.


Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Download Support Library
Have a look on few code snippets,

AndroidManifest.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.esri.arcgis.android.samples.helloworld"
  android:versionCode="1"
  android:versionName="1.0">

  <uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="19" />

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  <uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

  <application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:allowBackup="true" >


      <activity
          android:name=".DrawGraphicElements"
          android:configChanges="orientation"
          android:label="@string/app_name">

          <intent-filter>
              <action android:name="android.intent.action.MAIN" />

              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>
  </application>

</manifest>

DrawGraphicElements.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package com.esri.arcgis.android.samples.helloworld;

/**
 * Created by harshalbenake on 01/07/15.
 */
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapOnTouchListener;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.core.geometry.MultiPath;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.Polyline;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;

public class DrawGraphicElements extends Activity {

    /*
     * ArcGIS Android elements
     */
    MapView mapView = null;
    ArcGISTiledMapServiceLayer tiledMapServiceLayer = null;
    GraphicsLayer graphicsLayer = null;
    MyTouchListener myListener = null;

    /*
     * Android UI elements
     */
    Button geometryButton;
    Button clearButton;
    TextView label;

    /*
     * Other elements that hold app state
     */
    String mapURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyBasemap/MapServer";

    final String[] geometryTypes = new String[] { "Point", "Polyline",
            "Polygon" };

    int selectedGeometryIndex = -1;

    @SuppressWarnings("serial")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//      setContentView(mapView);
        setContentView(R.layout.main_draw);
        /*
         * Initialize ArcGIS Android MapView, tiledMapServiceLayer, and Graphics
         * Layer
         */
//      mapView = new MapView(this);
        mapView = (MapView)findViewById(R.id.map);
        myListener = new MyTouchListener(DrawGraphicElements.this, mapView);
        mapView.setOnTouchListener(myListener);

        /*
         * Initialize Android Geometry Button
         */
        geometryButton = (Button) findViewById(R.id.geometrybutton);
        geometryButton.setEnabled(false);
        geometryButton.setOnClickListener(new View.OnClickListener() {
            /*
             * This displays an AlertDilaog as defined in onCreateDialog()
             * method. Invocation of show() causes onCreateDialog() to be called
             * internally.
             */
            public void onClick(View v) {
                showDialog(0);
            }
        });

        label = (TextView) findViewById(R.id.label);

        clearButton = (Button) findViewById(R.id.clearbutton);
        clearButton.setEnabled(false);
        clearButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                graphicsLayer.removeAll();


                clearButton.setEnabled(false);
            }
        });

        /*
         * Initialize MapView, TiledMapServiceLayer and GraphicsLayer. This
         * block will be executed when app is started the first time.
         */
//      mapView.setExtent(new Envelope(-85.61828847183895, 38.19242311866144, -85.53589100936443, 38.31361605305102),0);

        tiledMapServiceLayer = new ArcGISTiledMapServiceLayer(mapURL);
        graphicsLayer = new GraphicsLayer();

        /*
         * Use TiledMapServiceLayer's OnStatusChangedListener to listen to
         * events such as change of status. This event allows developers to
         * check if layer is indeed initialized and ready for use, and take
         * appropriate action. In this case, we are modifying state of other UI
         * elements if and when the layer is loaded.
         */
        tiledMapServiceLayer
                .setOnStatusChangedListener(new OnStatusChangedListener() {
                    /*
                     * This callback method will be invokes when status of layer
                     * changes
                     */
                    public void onStatusChanged(Object arg0, STATUS status) {
                        /*
                         * Check if layer's new status = INITIALIZED. If it is,
                         * initialize UI elements
                         */
                        if (status
                                .equals(OnStatusChangedListener.STATUS.INITIALIZED)) {
                            geometryButton.setEnabled(true);
                        }
                    }
                });

        /**
         * Add TiledMapServiceLayer and GraphicsLayer to map
         */
        mapView.addLayer(tiledMapServiceLayer);
        mapView.addLayer(graphicsLayer);
    }

    /*
     * MapView's touch listener
     */
    class MyTouchListener extends MapOnTouchListener {
        // ArrayList<Point> polylinePoints = new ArrayList<Point>();

        MultiPath poly;
        String type = "";
        Point startPoint = null;

        public MyTouchListener(Context context, MapView view) {
            super(context, view);
        }

        public void setType(String geometryType) {
            this.type = geometryType;
        }

        public String getType() {
            return this.type;
        }

        /*
         * Invoked when user single taps on the map view. This event handler
         * draws a point at user-tapped location, only after "Draw Point" is
         * selected from Spinner.
         *
         * @see
         * com.esri.android.map.MapOnTouchListener#onSingleTap(android.view.
         * MotionEvent)
         */
        public boolean onSingleTap(MotionEvent e) {
            if (type.length() > 1 && type.equalsIgnoreCase("POINT")) {
                graphicsLayer.removeAll();
                Graphic graphic = new Graphic(mapView.toMapPoint(new Point(e.getX(), e
                        .getY())),new SimpleMarkerSymbol(Color.RED,25,STYLE.CIRCLE));
                //graphic.setGeometry();
                graphicsLayer.addGraphic(graphic);

                clearButton.setEnabled(true);
                return true;
            }
            return false;

        }

        /*
         * Invoked when user drags finger across screen. Polygon or Polyline is
         * drawn only when right selected is made from Spinner
         *
         * @see
         * com.esri.android.map.MapOnTouchListener#onDragPointerMove(android
         * .view.MotionEvent, android.view.MotionEvent)
         */
        public boolean onDragPointerMove(MotionEvent from, MotionEvent to) {
            if (type.length() > 1
                    && (type.equalsIgnoreCase("POLYLINE") || type
                    .equalsIgnoreCase("POLYGON"))) {

                Point mapPt = mapView.toMapPoint(to.getX(), to.getY());

                /*
                 * if StartPoint is null, create a polyline and start a path.
                 */
                if (startPoint == null) {
                    graphicsLayer.removeAll();
                    poly = type.equalsIgnoreCase("POLYLINE") ? new Polyline()
                            : new Polygon();
                    startPoint = mapView.toMapPoint(from.getX(), from.getY());
                    poly.startPath((float) startPoint.getX(),
                            (float) startPoint.getY());

                    /*
                     * Create a Graphic and add polyline geometry
                     */
                    Graphic graphic = new Graphic(startPoint,new SimpleLineSymbol(Color.RED,5));

                    /*
                     * add the updated graphic to graphics layer
                     */
                    graphicsLayer.addGraphic(graphic);
                }

                poly.lineTo((float) mapPt.getX(), (float) mapPt.getY());

                return true;
            }
            return super.onDragPointerMove(from, to);

        }

        @Override
        public boolean onDragPointerUp(MotionEvent from, MotionEvent to) {
            if (type.length() > 1
                    && (type.equalsIgnoreCase("POLYLINE") || type
                    .equalsIgnoreCase("POLYGON"))) {

                /*
                 * When user releases finger, add the last point to polyline.
                 */
                if (type.equalsIgnoreCase("POLYGON")) {
                    poly.lineTo((float) startPoint.getX(),
                            (float) startPoint.getY());
                    graphicsLayer.removeAll();
                    graphicsLayer.addGraphic(new Graphic(poly,new SimpleFillSymbol(Color.RED)));

                }
                graphicsLayer.addGraphic(new Graphic(poly,new SimpleLineSymbol(Color.BLUE,5)));
                startPoint = null;
                clearButton.setEnabled(true);
                return true;
            }
            return super.onDragPointerUp(from, to);
        }
    }

    /*
     * Returns an AlertDialog that includes names of all layers in the map
     * service
     */
    protected Dialog onCreateDialog(int id) {
        return new AlertDialog.Builder(DrawGraphicElements.this)
                .setTitle("Select Geometry")
                .setItems(geometryTypes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        graphicsLayer.removeAll();

                        // ignore first element
                        Toast toast = Toast.makeText(getApplicationContext(),
                                "", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.BOTTOM, 0, 0);

                        // Get item selected by user.
                        String geomType = geometryTypes[which];
                        label.setText(geomType + " selected.");
                        selectedGeometryIndex = which;

                        // process user selection
                        if (geomType.equalsIgnoreCase("Polygon")) {
                            myListener.setType("POLYGON");
                            toast.setText("Drag finger across screen to draw a Polygon. \nRelease finger to stop drawing.");
                        } else if (geomType.equalsIgnoreCase("Polyline")) {
                            myListener.setType("POLYLINE");
                            toast.setText("Drag finger across screen to draw a Polyline. \nRelease finger to stop drawing.");
                        } else if (geomType.equalsIgnoreCase("Point")) {
                            myListener.setType("POINT");
                            toast.setText("Tap on screen once to draw a Point.");
                        }

                        toast.show();
                    }
                }).create();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapView.pause();
    }
    @Override   protected void onResume() {
        super.onResume();
        mapView.unpause();
    }

}

main_draw.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <!-- MapView layout, including basemap layer, initial center point, and zoom level -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/geometrybutton"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/clearbutton"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/label"
        android:layout_gravity="center_horizontal" />

    <com.esri.android.map.MapView
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    mapoptions.MapType="Topo" />

</LinearLayout>

Thursday 22 October 2015

HB Blog 99: How To Integrate Urban Airship - Push Notification In Android And iOS???

Urban Airship is an American mobile technology company. It provides tools and services designed for mobile application developers to easily enhance their applications with audience engagement services, such as push notifications and integrated rich text notifications and in-app pages. Urban Airship primarily provides app developers the ability to easily add features such as creation and delivery of enhanced push notifications and a digital wallet, as well as reporting on the use of those features back to app developers. The company offers these services on Android, iOS, etc.
How to integrate Urban Airship push notification in Android: -

Add the SDK to your project in Android Studio: -
  1. Open your project in Android Studio
  2. Modify your application’s build.gradle script to include the Urban Airship Android Maven repository and dependencies:
  3.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    repositories {
        jcenter()
    
        maven {
            url  "http://dl.bintray.com/urbanairship/android"
        }
    }
    
    dependencies {
        // Urban Airship SDK
        compile 'com.urbanairship.android:urbanairship-sdk:6.1.+'
    
        // Recommended for in-app messaging
        compile 'com.android.support:cardview-v7:22.2.0'
    
        // Recommended for location services
        compile 'com.google.android.gms:play-services-location:7.5.0'
    
        // Required for Android (GCM) push notifications
        compile 'com.google.android.gms:play-services-gcm:7.5.0'
    }
    
  4. Sync the project with the gradle file.
Add the following permissions in Android Manifest: -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!-- REQUIRED for Urban Airship -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />  <!-- Required for Push -->

<permission android:name="${applicationId}.permission.UA_DATA" android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.UA_DATA" />
<!-- The two elements above ensure that only this application has access to the Urban Airship provider -->

<!-- OPTIONAL Urban Airship Settings -->
<!-- REQUIRED FOR LOCATION -->
<!-- Use ACCESS_COARSE_LOCATION if GPS access is not necessary -->
<!-- uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


Add the following services, provider, receivers, and activities under the application tag: -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!-- REQUIRED for Action.startActivityForResult -->
<activity android:name="com.urbanairship.actions.ActionActivity" />

<!-- REQUIRED for Urban Airship Push -->
<activity android:name="com.urbanairship.CoreActivity" />

<!-- REQUIRED for Urban Airship Push. The priority is important to be set lower than the
application's push intent receiver in order for the push intent receiver to handle push intents
before the core receiver. This allows the application to launch any activities before Urban
Airship performs any actions or falls back to launching the application launch intent. -->
<receiver android:name="com.urbanairship.CoreReceiver"
          android:exported="false">

    <intent-filter android:priority="-999">
        <action android:name="com.urbanairship.push.OPENED" />
        <category android:name="${applicationId}" />
    </intent-filter>
</receiver>

<!-- REQUIRED for Landing Pages
    - For more customization details, see com.urbanairship.actions.LandingPageActivity -->
<activity
    android:name="com.urbanairship.actions.LandingPageActivity"
    android:exported="false">

    <intent-filter>
        <action android:name="com.urbanairship.actions.SHOW_LANDING_PAGE_INTENT_ACTION" />

        <data android:scheme="http" />
        <data android:scheme="https" />
        <data android:scheme="message" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

<!-- REQUIRED for Urban Airship -->
<service android:name="com.urbanairship.push.PushService" android:label="Push Notification Service" />

<!-- Required for analytics -->
<service android:name="com.urbanairship.analytics.EventService" android:label="Event Service" />

<!-- Required for Actions -->
<service android:name="com.urbanairship.actions.ActionService" />

<!-- Required for Rich Push -->
<service android:name="com.urbanairship.richpush.RichPushUpdateService" />

<!-- OPTIONAL for Urban Airship Location (for segments support) -->
<service android:name="com.urbanairship.location.LocationService" android:label="Segments Service" />

<!-- This is required for persisting preferences related to push and location -->
<provider
    android:name="com.urbanairship.UrbanAirshipProvider"
    android:authorities="${applicationId}.urbanairship.provider"
    android:permission="${applicationId}.permission.UA_DATA"
    android:exported="true"
    android:multiprocess="true" />


Create a new airshipconfig.properties file with your application’s settings: -
developmentAppKey = Your Development App Key
developmentAppSecret = Your Development App Secret
productionAppKey = Your Production App Key
productionAppSecret = Your Production Secret
# Toggles between the development and production app credentials
# Before submitting your application to an app store set to true
inProduction = false
# LogLevel is "VERBOSE", "DEBUG", "INFO", "WARN", "ERROR" or "ASSERT"
developmentLogLevel = DEBUG
productionLogLevel = ERROR


Starting Urban Airship Services: -
The Urban Airship SDK requires only a single entry point in the application, known as takeOff. To start, create a class that extends Application and set the name of the class for the application entry in the AndroidManifest.xml:
1
<application android:name=".CustomApplication" ... />

Then, override the application’s onCreate to call UAirship.takeOff:
1
2
3
4
@Override
public void onCreate() {
    UAirship.takeOff(this);
}

This will bootstrap the SDK and look for the settings in airshipconfig.properties. These can also optionally be provided at run time by passing an AirshipConfigOptions in the call to UAirship.takeOff:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Override
public void onCreate() {
    AirshipConfigOptions options = new AirshipConfigOptions();
    options.developmentAppKey = "Your Development App Key";
    options.developmentAppSecret = "Your Development App Secret";
    options.productionAppKey = "Your Production App Key";
    options.productionAppSecret = "Your Production App Secret";
    options.inProduction = false;
    UAirship.takeOff(this, options);
}

Enabling User Notifications :-
The Channel ID is a unique identifier that ties together an application/device pair on Android and Amazon devices. The Channel ID is used to target pushes to specific devices using the Urban Airship API. Once a Channel ID is created, it will persist the application until it is either reinstalled, or its internal data is cleared. The Channel ID will be logged for all apps. You can always get the Channel ID with a couple of extra lines to your application.
The Urban Airship SDK makes a distinction between “user notifications”, which can be seen by the user, and other forms of push that allow you to send data to your app silently, or in the background. Enabling or disabling user notifications is a preference often best left up to the user, so by default, user notifications are disabled. For testing purposes, enabling notification at startup requires a few extra lines of code to your main application class.
After UAirship.takeOff, call:
1
2
3
String channelId = UAirship.shared().getPushManager().getChannelId();
Logger.info("My Application Channel ID: " + channelId);
UAirship.shared().getPushManager().setUserNotificationsEnabled(true);

How to integrate Urban Airship push notification in iOS: -
Download and unzip the latest version of libUAirship into the same directory as your project. You should see a new directory, named Airship, containing the latest version of the libUAirship static library and headers, as well as an AirshipKit directory, containing an Xcode project that builds the AirshipKit embedded framework.
Before you begin, make sure both the AirshipKit and Airship directories are in the top level of your app’s source directory.
  1. Include AirshipKit as a project dependency - Drag AirshipKit.xcodeproj out of the AirshipKit folder and into your app project in Xcode (directly under the top level of the project structure). Now AirshipKit will be built at compile-time for the active architecture.
  2. Link against the embedded framework - To link against the embedded framework, add the AirshipKit.framework file to the Embedded Binaries section in the General tab for your target. This should also add it to the Linked Frameworks and Libraries section.
  3. Check Linked Frameworks and Libraries - Make sure AirshipKit.framework shows up in the Linked Frameworks and Libraries section in the General tab for your target.
Create AirshipConfig.plist: -
The Urban Airship SDK uses a .plist configuration file named AirshipConfig.plist to manage your production and development application profiles.
  1.     Create two applications within your Urban Airship account: One for development and one for production.
  2.     Create an AirshipConfig.plist file.
  3.     Set the following values to the ones in your applications
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>inProduction</key>
  <false/>
  <key>developmentAppKey</key>
  <string>Your Development App Key</string>
  <key>developmentAppSecret</key>
  <string>Your Development App Secret</string>
  <key>productionAppKey</key>
  <string>Your Production App Key</string>
  <key>productionAppSecret</key>
  <string>Your Production App Secret</string>
</dict>
</plist>

Starting Urban Airship Services: -
The Urban Airship SDK requires only a single entry point in the app delegate, known as takeOff. Inside your application delegate’s application:didFinishLaunchingWithOptions: method, initialize a shared UAirship instance by calling [UAirship takeOff]. This will bootstrap the SDK and look for settings specified in the AirshipConfig.plist file you created earlier.

Import the Required Header Files: -
1
2
3
4
5
#import "UAirship.h"
#import "UAConfig.h"
#import "UAPush.h"
#import <AirshipKit/AirshipKit.h>
@import AirshipKit;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Populate AirshipConfig.plist with your app's info from https://go.urbanairship.com
    // or set runtime properties here.
    UAConfig *config = [UAConfig defaultConfig];
    // You can also programmatically override the plist values:
    // config.developmentAppKey = @"YourKey";
    // etc.
    // Call takeOff (which creates the UAirship singleton)
    [UAirship takeOff:config];
}
//Retrieving your Channel ID
//The Channel ID is a unique identifier that ties together an application/device pair on iOS devices. The Channel ID is used to target pushes to specific devices using the Urban Airship API.
NSString *channelId = [UAirship push].channelID;
NSLog(@"My Application Channel ID: %@", channelId);

    

Enabling User Notifications:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Set the notification types required for the app (optional). This value defaults
// to badge, alert and sound, so it's only necessary to set it if you want
// to add or remove types.
[UAirship push].userNotificationTypes = (UIUserNotificationTypeAlert |
                                         UIUserNotificationTypeBadge |
                                         UIUserNotificationTypeSound);

//To enable user notifications programmatically
// User notifications will not be enabled until userPushNotificationsEnabled is
// set YES on UAPush. Once enabled, the setting will be persisted and the user
// will be prompted to allow notifications. Normally, you should wait for a more appropriate
// time to enable push to increase the likelihood that the user will accept
// notifications.
[UAirship push].userPushNotificationsEnabled = YES;

Sunday 18 October 2015

HB Blog 98: Go Programming Language - Google's Open Source Project.

Go, also commonly referred to as golang, is a programming language, an open source project developed at Google. It is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.
Go was born out of frustration with existing languages and environments for systems programming. Programming had become too difficult and the choice of languages was partly to blame. One had to choose either efficient compilation, efficient execution, or ease of programming; all three were not available in the same mainstream language. Programmers who could were choosing ease over safety and efficiency by moving to dynamically typed languages such as Python and JavaScript rather than C++ or, to a lesser extent, Java.

Go is an attempt to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aims to be modern, with support for networked and multicore computing. Finally, it is intended to be fast: it should take at most a few seconds to build a large executable on a single computer. To meet these goals required addressing a number of linguistic issues: an expressive but lightweight type system; concurrency and garbage collection; rigid dependency specification; and so on. These cannot be addressed well by libraries or tools; a new language was called for.

It is a statically-typed language with syntax loosely derived from that of C, adding garbage collection, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. Although it borrows ideas from existing languages, it has unusual properties that make effective Go programs different in character from programs written in its relatives. A straightforward translation of a C++ or Java program into Go is unlikely to produce a satisfactory result—Java programs are written in Java, not Go. On the other hand, thinking about the problem from a Go perspective could produce a successful but quite different program. In other words, to write Go well, it's important to understand its properties and idioms. It's also important to know the established conventions for programming in Go, such as naming, formatting, program construction, and so on, so that programs you write will be easy for other Go programmers to understand.
Refer below link to download the Go distribution:-
https://golang.org/dl/

Project structure:-
 Go code must be kept inside a workspace. A workspace is a directory hierarchy with three directories at its root:
    src contains Go source files organized into packages (one package per directory),
    pkg contains package objects, and
    bin contains executable commands.

The go tool builds source packages and installs the resulting binaries to the pkg and bin directories.
The src subdirectory typically contains multiple version control repositories (such as for Git or Mercurial) that track the development of one or more source packages.

To give an idea of how a workspace looks in practice, here's an example:

bin/
    hello                          # command executable
    outyet                         # command executable
pkg/
    linux_amd64/
        github.com/golang/example/
            stringutil.a           # package object
src/
    github.com/golang/example/
        .git/                      # Git repository metadata
    hello/
        hello.go               # command source
    outyet/
        main.go                # command source
        main_test.go           # test source
    stringutil/
        reverse.go             # package source
        reverse_test.go        # test source


This workspace contains one repository (example) comprising two commands (hello and outyet) and one library (stringutil).
A typical workspace would contain many source repositories containing many packages and commands.
Commands and libraries are built from different kinds of source packages.

Check that Go is installed correctly by building a simple program, as follows.
Create a file named hello.go and put the following program in it:
package main
import "fmt"
func main() {
    fmt.Printf("hello, world\n")
}

Then run it with the go tool:
$ go run hello.go
hello, world

If you see the "hello, world" message then your Go installation is working.

An interactive introduction to Go in three sections. The first section covers basic syntax and data structures; the second discusses methods and interfaces; and the third introduces Go's concurrency primitives. Each section concludes with a few exercises so you can practice what you've learned.
Refer below link to download the Go distribution:-
https://tour.golang.org/