Wednesday, September 30, 2015

JSONStore - an overview

JSONStore is a feature used in IBM Worklight. This adds ability to store JSON documents in Worklight Applications. 

JSONStore is a light weight document-oriented storage system that is included as a feature of IBMWorklight foundation enables persistent storage of JSON documents. Documents in application are available in JSONStore even when the device that running the application offline. This persistent always available storage can be useful for customers, employees or partners, to give them access to when, for e.g. there is no network to the device. 



References:

Git Learning Part III - Viewing Old Commit

git checkout command serves three functions. Checking out files, checking out commits, checking out branches. Checking out a commit makes the entire working directory match that commit. This can be used to view the old state of the project without altering the current state in anyway. Checking out a file let us see an old version of the particular file, leaving rest of the working directory untouched. 

usage is 

git checkout master 

the above command returns to the master branch. 

other example usages are 

git checkout => Checkout the previous version of the file. This turns the that resides in the working directory into an exact copy of one from the and adds to the staging area 

git checkout   => Updates all files in the working directory to match the specified commit. We can use either a commit hash or tag as the element. This will put in a detached HEAD state. 

In Simple words, Git checkout is an easy way to load any of the saved snapshots on the development machine.  

Checking out an old commit is a read-only operation. Its impossible to harm the repository while viewing an old revision. The “current” state of the project remain untouched in the master branch. During normal course of development HEAD points to master or some other local branch. but when we checkout a previous commit, HEAD no longer points to a branch - it points directly to a commit. This is called detached HEAD state. 

Checking out an old file does affect the current state of the repository. One can re-commit the old version in a new snapshot as he would with any other file. So, in effect, the git checkout serves as a way to revert back to an old version of an individual file. 

The example given is good one that illustrate this, 

Consider we have a repo that 

b7119f2 Continue doing crazy things
872fa7e Try something crazy
a1e8fb5 Make some important changes to hello.py
435b61d Create hello.py
9773e52 Initial import

If we want to look at the a1e8fb5 again and decide after doing some tests, below can be done 

git checkout a1e8fb5

This above makes the working directory exact state as a1e8fb5 commit. One can look at the files, compile project, run tests, and even edit the files without worrying about losing current state of the project. 

to continue developing, we can get back to the current state of the project, by 

git checkout master 


If anything to be reverted at this point, we can use the git revert or git reset command. 

References:

Sunday, September 27, 2015

Framework Changes in iOS 9.0

AV Foundation Framework: 

Provides a new API AVSpeechSynthesize that lets an app to specify voice by identifier, instead by language. We can also specify name and quality properties to get information about voice. 

AVKit framework 
Includes a PictureInPictureController And AVPlayerViewController class, which helps to participate in Picture In Picture. 

CloudKit Framework
IF one is having a cloud kit app, we can now use the CloudKit web services or CloudKit JS, a javascript library, to provide web interface to users to access the same data as the app. We must have a schema defined and created already for the web interface to fetch, and delete records, zones and subscription. 

Foundation Framework: 
- APIs for on demand loading of NSBundle resources
- Strings file support for context-dependant variable width strings 
- NSProcessInfo APIs for power and thermal management.

HealthKit framework:
- New support for tracking areas such as reproductive health and UV exposure. 
- New support for bulk deleting entries and deleted entries. 

Local Authentication framework:
- The ability to get the representation of current set of enrolled fingers so that app can change behavior when a finger is enrolled or removed.
- Support for canceling a user prompt from code
- Support for evaluating keychain access control lists and use of an authentication context in keychain calls. 
- Support for reusable Touch ID matches. 

MapKit framework
- MapKit supports querying transit ETAs and launching maps into transit directions
- Map Views support a 3D flyover mode 
- Annotations can be fully customized 
- Search results for MapKit and CLGeocoder can provide a timezone for the result 

PassKit framework 
- In iOS 9.0, Apple pay supports Discover cards and store debit and credit cards 
- Card issuers and payment networks can add cards to Apple Pay directly in their apps 

Safari Services Framework 
- SFSafariViewController can be used to display web content within the app. It shares cookies and other website data with Safari and has many of Safari’s great features such as auto fill and Safari reader. Unlike Safari itself, SFSafariViewController is tailored for displaying a single page, featuring a Done button that takes user back to where they were in the app. 

IF the app displays web content but does not customize content, then app can consider replacing the WKWebView or UIWebView based browsers with SFSafariViewController. 

UIKit framework changes
There are a number of UIKit changes, but most noticeable ones are

- The UIStackView class lets application to organize a set of subviews as a stack that can be arranged vertically or horizontally.
- A New UIApplicationDelegate method which lets to open a document in place instead of working with a copy of it. To support this feature, app needs to add the key LSSupportsOpeningDocumentsInPlace with a value of YES in the info.plist file. 
- The new behavior property UIUserNotificationAction, which lets to support text input from user’s notifications. 
- The new NSDataAsset class, which makes it easy to fetch contents tailored to the memory and graphics capabilities of the device.  

The below are the main deprecations in the iOS 9.0 SDK 

- Addressbook and Addressbook UI frameworks, instead application now need to use the Contacts and Contacts UI frameworks instead. 
- NSURLConnection is deprecated, instead, we need to use NSURLSession APIs. 


References:

Saturday, September 26, 2015

IBM Worklight - a sneak peek

IBM work light provides an open, comprehensive and advanced mobile application platform for smartphones and tablets, helping organizations of all sizes to efficiently develop, connect, run and manage HTML5, hybrid and native applications Leveraging standards based technologies and tools. The platform ships with a comprehensive development environment, mobile-optimized middle ware and integrated management and analytics console supported by a variety of security mechanisms. 

IBM work light enables creation of rich, cross-platform apps without the user of code translation, proprietary interpreters or unpopular scripting languages while reducing the time to market cost and complexity of development and enabling a better user experience across a variety of mobile devices. 

IBM work light is a part of IBM Mobile foundation family of products that provides the essential elements needed for complete mobile development, deployment and management within a business. 

Below are the components included in the IBM work light 

WorkLight Studio

As Eclipse based IDE allowing developers to perform all the coding and integration tasks that are required to develop fully operational application

IBM work light server
The Java based server is a scalable gateway between applications external services and the enterprise backend infrastructure. the server contains security features to enable connectivity multi source data extraction and manipulation, authentication, direct update of web and hybrid apps analytics and operational management functions. 

IBM work light device runtime components 
Client side runtime environment that embeds server side functionality within the target-environmnent of deployed apps. 

Work light console : a Web based ui for on going monitoring and administration of the work light server and its deployed apps, adapters and push notifications. 



refences:

What is ATS (App Transport Security) in iOS 9.0 - A brief overview

ATS enforces best practices in the secure connections between app app and the backend. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. ATS is by default in iOS 9.0 and OS X v 10.11. 

If developing a new app, HTTPS should be the one default. In addition, communication through high level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. IF app try to make a connection that doesnt follow these requirements, an error will be thrown. IF the app needs to make connection to an insecure domain, app has to specify this domain in the info.plist file.   

references:

Git Learning Part I - Setting up a repository

Git init command creates a new Git repository. It can be used to convert and existing unversioned project to a Git repository or initialize a new empty repository. 

Executing git init creates a .git subdirectory in the project root, which contains all of the necessary metadata for the repo. Aside from the git subdirectory, an existing project remain unaltered (unlike SVN, git doesnt require a .git in every sub directory) 

The init command variants are 

git init => create git repository at the current path 
git init Initializes the git with an empty directory 
git init —-bare create a shared repository. Repositories initialized with —-bare flag end with .git. For e.g. the bare version of a repository called my-project should be stored in a directory called my-project.git 

Bare flag creates a repository that doesnt have working directory. This makes impossible to edit files and commit in that repository. Central repositories should be always created as a bare repositories because pushing branches to a non-bare repository has the potential to overwrite the changes. We can think of bare as a way to mark a repository as a storage facility as opposed to development environment. This means that virtually for all work flows, the central repository is bare, and developers local repositories are non-bare. 

Below is the most common use case: 

ssh
cd path/repo
git init —-bare my-project.git 

Developers can then clone the repository to create a local copy in their development machine. 

git clone command copies an existing Git repository. This is similar to svn checkout, except that the “working copy“ is full fledged git repository. it has its own history manage its own files and is a complete isolated environment from the original repository.

git config command lets us configure Git installation (or and individual repository) from the command line. This command can define everything from user info to preferences to the behavior of a repository. Some of the configuration options are 

got config —-global user.name
git config —-global user.email
git config —-system core.editor

references:

How Chromecast works


Chromecast gets things to the TV screen from a remote device in part by using something called DIAL (Discovery and Launch Protocol). DIAL was jointly developed by Netflix and Youtube, which is owned by Google. DIAL was actually launched in Google TV, and now it is available in other devices and apps. 

One of the Chromecast’s components, the DIAL Service Discovery Protocol, uses Simple Service Discovery Protocol (SSDP) version 1.1, which is developed by UPnP (Universal Plug and Play), to allow a DIAL client device to locate a DIAL server device running on same network. The other component is the DIAL REST which is used to query, launch or stop applications using HTTP requests from the client device to the server device. 

In case of Chromecast, the phone is the DIAL client and the chromecast device itself is the server. 

Google Created Google Cast Screen sharing technology to work on top of DIAL, adding lot more functionality than DIAL could offer alone. There is a Google Cast SDK which enable developers to add related functionality to third party apps that can be used to launch media from the client to the chromecast. 


Chromecast is actually running a pared-down version of Chrome browser, and the applications running on device are web applications that receive above mentioned HTTP requests and act accordingly. 

References:
http://electronics.howstuffworks.com/chromecast4.htm

Android App in full screen

The Aim was to make a single activity full screen. for this, on the specific activity, done the below programmatically. 

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_clock);

09-26 11:57:38.370  14828-14828/livingmobile.com.eyeome E/AndroidRuntime FATAL EXCEPTION: main
Process: livingmobile.com.eyeome, PID: 14828
java.lang.RuntimeException: Unable to start activity ComponentInfo{livingmobile.com.eyeome/livingmobile.com.eyeome.ClockActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content

Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:302)

Some of the options mentioned were to call the requestFeature before the super.onCreate method. 
This intact worked. 

Other options mentioned where to set the theme as 

android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen"

android:name="livingmobile.com.eyeome.ClockActivity"
android:label="@string/title_activity_clock"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

However, if the total application theme is 

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:113)
at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
at livingmobile.com.eyeome.ClockActivity.onCreate(ClockActivity.java:34)


We can specify the app theme to be AppCombat as specified in one of the below links.

References:

Friday, September 25, 2015

Android Centering Text views to the center of the Activity

Using relative layout, it can be kind of achieved using the layout parameter keys such as

"http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#000000"
android:id="@+id/rel1">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10"
android:textSize="65dp"
android:textStyle="bold"
android:id="@+id/textView"
android:textColor="#ffffff"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":"
android:textSize="65dp"
android:textStyle="bold"
android:id="@+id/textView1"
android:layout_toRightOf="@+id/textView"
android:textColor="#ffffff"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="20"
android:textSize="65dp"
android:textStyle="bold"
android:id="@+id/textView3"
android:layout_toRightOf="@+id/textView1"
android:textColor="#ffffff"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="am"
android:textSize="45dp"
android:textStyle="bold"
android:id="@+id/textView4"
android:layout_toRightOf="@+id/textView3"
android:layout_alignBaseline="@+id/textView"
android:textColor="#ffffff"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saturday, Sep 29"
android:textSize="35dp"
android:textStyle="bold"
android:id="@+id/textView5"
android:layout_below="@+id/textView"
android:textColor="#ffffff"/>



references
http://www.tutorialspoint.com/android/android_relative_layout.htm

Thursday, September 24, 2015

Java PNS Multi threading - sending to multiple devices

Apparently, sending to multiple devices is quite easy in and the code is like below. 

When tried this, below two observations i had

1. With the threading, code that is compiled in MAC when moved to Windows, it appears that the message is not sent properly. Probably we need to compile on Windows Java compiler itself? 
2. It appeared that if no multi threading, the whole program holds and continue after only the message is sent.
3. Without multi threading if application is trying to create a new thread and send the message, 

public void send (List devices, Object keystore, String password, boolean production) {
    
    /* Prepare a simple payload to push */
    PushNotificationPayload payload = PushNotificationPayload.alert("Hello World!");
    
    
    /* Decide how many threads you want to create and use */
    int threads = 30;
    
    
    /* Start threads, wait for them, and get a list of all pushed notifications */
    List notifications = Push.payload(payload, keystore, password, production, threads, devices);
    
    
}



References:
https://code.google.com/p/javapns/wiki/PushNotificationAdvanced

Sunday, September 20, 2015

Essentials of Swift - Learning Part I

Basic Types: Swift uses let to make constants and var to make the variables. 

var myvariable = 42
let myconstant = 42

Every constants and variable has type in Swift. However, it is inferred and no need to be specified explicitly. 

If the initial value doesnt provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by semi colon. 

let explicitDouble : Double = 70

Values are never implicitly converted to another type. IF we need to convert a value to a different type, explicitly make an instance of desired type. Here, we are converting an int to String 

let label = “Width is”
let widthLabel = label + String (width)

We have an () & \ string interpolation way like below 

let apples = 3
let orange = 2
let apple summary = “i have \(apples) apples”
let fruitSummary = “i have \(apples+orange) fruits”

We can work with Optionals if the value may be missing. An optional value either contains a value or a nil to indicate the value may be missing. We need to write ? after the type of the value to indicate that it is optional. 

let optionalInt : Int? = 0

To get the underlying value form the optional, we just need to unwrap it. the ! is called forced unwrap operator. 

let actualInt: Int = optionalInt!

let myString = “7”
let myString2 = “one”

var possibleInt = Int(myString)
var possibleInt2 = Int(myString2)

print(possibleInt) 
print(possibleInt2)

the above will output as 7 and nil. 

Below is how we can declare an array 

var ratingList = {“poor”, “average”, “good”}
If we want to create an empty array, use the initialize syntax. 
let emptyArray = [String]()

References:

DNS64/NAT64 Transitional workflow

As more clients are using IPv6, the operator must support both IPv4 and IPv6. Ideally providers want to drop support for the IPv4 network. However, doing so prevents clients from accessing IPv4 servers, which represents a significant portion of the internet. To solve this problem, most major network providers are implementing a DNS64/NAT64 transitional workflow. 

In this typical flow, the client sends DNS queries to a DNS64 server, which requests IPv6 addresses from the DNS server. When an IPv6 address is found, it is passed back to the client immediately. However, when an IPv6 address is not found, the DNS64 server requests and IPv4 address. DNS64 server then synthesizes an IPv6 address by prefixing IPv4 address, and passes back to the client. In this regard the client always receives and IPv6 ready address. 

Below is the sequence diagram showing the overall procedure 



When the client sends a request to server, any IPv6 packets destined for synthesized addresses are automatically routed by the network through a NAT64 gateway. The gateway performs IPv4 to IPv6 translation for the response from the server. 

References:

Git Learning Part II Inspecting a repository

Git status command displays the status of the working directory and the staging area. This doesnt give any information regarding the committed project history. Instead it gives info only about the changes in the staging area which have been staged, which havent been and which files have been tracked by Git. 

to use status command, can just use 

git status

Running this command on one Linphone git directory, below is what is seen. 

Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)

modified:   Classes/LinphoneManager.m
modified:   Resources/linphonerc~ipad
modified:   linphone-Info.plist
modified:   linphone.xcodeproj/project.pbxproj
modified:   submodules/belle-sip (modified content)
modified:   submodules/linphone (modified content)

no changes added to commit (use "git add" and/or "git commit -a")

Ignoring Files : There can be two types of files those can be ignored. Those could be the ones just added or could be the ones that doesnt need to be committed to the git. The git status command will print both these types if the latter is not added to the ignore list. To add to the ignore list, these file paths can be specified in a .gitignore file. Below is a sample in which the Classes/LinphoneManager.m is excluded from appearing in the git status output. 

build-*
*.locuser
.DS_Store
liblinphone-sdk
liblinphone-iphone-sdk*.zip
xcuserdata/
Classes/LinphoneIOSVersion.h
Pods/
build
test-reportl
Classes/LinphoneManager.m

The Git log command displays the committed snapshots. this lets to list the project history, filter and search for the specific changes. Like mentioned earlier, git log command only works on the committed changes not in the working directory unlike the git status command. 

Some of the git log commands are like below

git log 
git log -n
git log —-onleline 
git log —stat => Displays which files are in each commit
git log -p => Displays patch of each commit 

git log —-author=“authorpattern>”
git log —-grep=“grep pattern>”
git log since> Shows only occurrence between a committ ID, branch name HEAD or any commit reference
git log file => Displays only commits that occur in a specific file. 
git log —-graph —-decorate —-oneline => Displays a text based graph to the left of the commit. —decorate adds the names of branches or tags of the commits that are shown. 

When listing the commit details it will be something like below 

commit 89a4eef409b30ab4007dbb704be2dfb3791e445b
Author: Steve keexo
   
In this the ID is the SHA-1 checksum of commits contents. this serves as unique ID and integrity of the content. 

References:



Tuesday, September 15, 2015

IPv6 address format

IPv4 and IPv6 uses different formats: 

Address space: 128 in IPv6 and 32 in IPv4
Representation : String representation in IPv6 while it is integer representation in IPv4
Length: Including field separators it is 39 in IPv6, while it is 15 in IPv4 
Notation: Hexadecimal notation in IPv6, while it is decimal in IPv4

Below given are some bullet points on the benefits of IPv6 over IPv4

- larger address space
- simplified header format 
- automatic configuration
- more efficient routing 
- improved quality of service and security 
- compliance with regulatory requirements
- widespread use in global markets 

Below given few examples of IPv6 addresses: 

FE80:0000:0000:0000:0202:B3FF:FE1E:8329 => 128 bit address in eight 16bit in the format global:subnet:interface
FE80::0202:B3FF:FE1E:8329 => example of a collapsed address where two consecutive colons represent 16bit blocks that contain zeros. 
[2001:db8:0:1]:80 => with a port number. brackets can be omitted if the port number is not present 
http://[2001:db8:0:1]:80 => URL containing IPv6 address. 

references:

Friday, September 11, 2015

Exploring Java PNS

The source and the libraries required were downloaded form the link from the reference section. this is a library which allows us to send APNS messages from java library. 
JavaPNS require 1.5 runtime or later. 

there are few dependancies with this, and they are 

bcprov-jdk15-146.jar => Bouncy Castle library used for Secure connection with the Apple server
log4j-1.2.17.jar => Apache Logging framework 

The above are to be in the class path for this to work along with the Java PNS library jar file which is JavaPNS_2.2.jar

The Java PNS package downloaded also had a test application which is NotificationTest.java 

ran this with the respective arguments and it sent the push message to the app successfully. 


References:

Wednesday, September 9, 2015

MKMapView and MKMapCamera Few notes


MKMapView provides embedded map interface. When initializing Mapview, we should provide a regionn. A region is defined by a center and a horizontal and vertical distance referred to as span. The span defines how much of the map at a given point should be visible and is also how you set the zoom level. Specifying a small span results in the user seeing a more narrow geographical area and corresponds to a higher zoom level. 

An annotation object is any object that conforms to MKAnnotation protocol. The presentation of annotation objects on the map is using MKAnnotationView. Because annotation view are needed only when they are on the screen. Annotation views with a reuse identifier can be detached and queued internally by the map view when they move offscreen. This feature improves memory use by keeping only a small number of annotation views in memory at once and by recycling recycling the views you do have. 

For adding overlays to the Map, we need to have overlay object which conforms to the MKOverLay protocol. An overlay object is a data object that contains the points needed to specify the shape and size of the overlay and its location on the map. Overlays can represents shapes such as Circles, rectangles, multi-segment lines and simple or complex polygons. Developer can also define custom overlays. the presentation of Overlay is done by the MKOverlayRenderer class. 

When configuring the map, the overlay objects can be added at any time. The map view uses data in each overlay object to determine when corresponding overlay view needs to appear on screen. When an overlay moves on screen, the map view asks its delegate to create a corresponding overlay renderer. 

MKMapCamera object describes a virtual camera that we can use to define the appearance of the map. A camera object creates a virtual viewpoint above the map surface and affects how the map renders its tiles and other content. We can use camera object to specify the location of the camera on the map, the compass heading that corresponds to camera’s viewing direction, the pitch of the camera relative to the map perpendicular and camera’s altitude above the map. These factors let the map to appear like 3D. 

Map can be centered with the MKMapCamera’s centerCoordinate property. 

References:

Tuesday, September 8, 2015

Google Cloud Messaging on iOS

Google provides a sample app that details the procedure

Step 1:

sudo gem install cocoapods 

This installs the cocoapods

After this run the below command to get the Google project 

pod try Google 

This basically checks out all the sample apps in cocoapods under Google. 

Step 2: 

Next Step was to get the configuration file 

For this step, had to enter the bundle ID that has the APNS feature and also has the p12 certificate
Now, the console asked the p12 certificate and after uploading the certificate, go the GCM server key and the sender ID

Then had to enable which services to be enabled. Selected the Google Cloud Messaging and moved on. Below few screenshots details the process involved





finally, this gave the GoogleServices-Info.plist file. 

This file was added to all the targets and ran the app on the device. This successfully registered the APNS and there is a Google token also associated with it. 

Now run the Server Demo app and give the registration token and the server API key and the message should appear on the app. 

References:

Sunday, September 6, 2015

Google Cloud Messaging - Learning Part 1


This enables to send the message to the devices from the server and receive message from the users device on the same connection. The GCM handles all aspects of queuing of message and delivery to client applications running on target devices, and its completely  free. 

Below are the main features of this 

1. Versatile messaging targets : Distribute message to the client app in any of three ways - to single devices, to group of devices, or to devices subscribed to topics. 
2. Downstream messaging : For purposes such as alerting users, chat messaging or kicking off background processing before user opening the app, GCM provides a battery efficient connection between server and devices 
3. Upstream messaging : Send ACKs, chats, and other messages from devices back to the servers over GCM’s reliable and battery efficient connection channel. 

Sending a message using GCM-HTTP connection server protocol: 

https://gcm-http.googleapis.com/gcm/send 
Content-Type:application/json
Authorization:key=AISS….. 
{
“to” : “/topics/foo-bar”,
“data” : 
{
“message” : “This is a GCM topic message”,
}

}

To Handle a downstream message on an Android device, below is the code 

@override 
public void onMessageReceived (String from, Bundle data)
{
String message = data.getString(“message”);
}

References:

Thursday, September 3, 2015

MKMapView - Custom View for Annotation

First step is to have MKMapView delegate set and override the viewForAnnotation method 
Next is to create annotation 

thePlane = [[MKPointAnnotation alloc] init];
    thePlane.coordinate = startPoint;
    thePlane.title = @"Agent";
    [self.mapView addAnnotation:thePlane];


- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    static NSString *SFAnnotationIdentifier = @"AnnotationIdentifier";
    MKPinAnnotationView *pinView =
    (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:SFAnnotationIdentifier];
    if (!pinView)
    {
        MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                         reuseIdentifier:SFAnnotationIdentifier];
        UIImage *flagImage = [UIImage imageNamed:@"car.png"];
        annotationView.centerOffset = CGPointMake(0, -16);
        // You may need to resize the image here.
        annotationView.image = flagImage;
        return annotationView;
    }
    else
    {
        pinView.annotation = annotation;
    }
    return pinView;

}

references:
https://gist.github.com/siqin/3175036