Monday, June 30, 2014

Toq SmartWatch from Qualcomm

The Qualcomm TOQ SDK is designed to allow developers to enable interaction and communication between Android apps and the Qualcomm TOQ smart watch. When the android app is on the same device as the Qulcomm TOQ Android app, it can use the Toq app to interact with the TOQ smart watch. This allows developers to give consumers the ability to customise their Toq experience by adding their app as an on-watch display option. The TOQ app process incoming third-party API calls and communicates directly with the SmartWatch. 

The TOQ SDK offers below functionalities

- Request permission to become Toq - enabled 
- Send notifications to TOQ watch 
- Install., update or delete applets on the Toq watch

The Qualcomm Toq smart watch is different from others because of the revolutionary Qualcomm Mirasol display which offers superior readability, even in bright sunlight. It utilises the reflected light to create its images instead of back light. This makes it extremely low power device and suitable for always on use case. 


References: 
https://developer.qualcomm.com/mobile-development/create-connected-experiences/smartwatch-toq-sdk

Uniform Type Identifiers

UTIs (short for Unifrom Type Identifiers) is Apple's answer to identify data handled within the system. In brief, UTI is a unique identifier for a particular type of data or a file. For e.g. com.adobe.pdf represents a PDF document and public.png represents a PNG image. Whenever user opens this type of file, iOS hands off that file to specific app. 

System will allow multiple apps to register with the same UTI. In this case, OS will show a prompt with the list of capable apps that can open that file. For e.g. when share a PDF document, the OS will be shown a prompt with the options such as iBooks, RaddleDocs, Chrome, EasyPrint, Kindle, Dropbox, etc. 



Below is the image which is popped up by the OS when Airdrop file is received. 



References:

Sunday, June 29, 2014

Airdrop - iOS 7. Programming

The UIActivityController class bundled in the iOS 7 SDK makes it simple for developers to integrate Airdrop feature into the applications. The application just needs to tell this class the objects it want to share and the UIActivityController will take care of the rest. 

Airdrop uses Bluetooth to scan nearby devices. When a connection is established via bluetooth, it will create an Adhoc WiFi network to link both the devices together allowing faster data transmission. It doesn't mean that the devices must be connected to the WiFi network but the WiFi device needs to be on for the data transfer. 

A UIActivityController is a standard view controller that provides several standard services such as copying item to clipboard, Sharing content to social media sites, sending items via messages etc. In iOS 7.0 SDK, this class comes with Airdrop feature built in. 

UIActivityController *controller = [[UIActivityController alloc]initWithActivityItems:objectsToShare applicationActivities:nil] ;
[self presentViewCotnroller:controller animated:YES completion:nil];

Optionally an application can exclude certain types of activities by providing excludeActivities Array. 

NSArray *excludeActivites = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook, UIActivityTypePostToWeibo,UIActivityTypeMessage
    UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteBoard, UIActivytTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivtyTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWebo]

controller.excludedActivityTypes = excludedActivities; 

The above code will let the ActionSheet show only Airdrop in the action sheet 

Inorder to share the content from the application to the Airdrop recipient, application just needs to provide the correct path of the source application. For e.g. if the application is having the file in the Documents folder, Full path upto this folder needs to be passed. 


When the file is received on the other device, it get opened in the application which is registered in the corresponding content type. For e.g. if we just pass a string, it opens in note application. If its a pdf file it opens up in Safari, an image in Photos app. This is done using the UTI (Uniform Type Identifier. Each application would have registered using the corresponding type identifiers and OS will launch the corresponding app.

References:

Saturday, June 28, 2014

Android One - Low End Smartphones

Current problem with phone manufacturers those who are trying to produce low cost phones is that a lot of tweaks needs to be applied on the hardware in order to fit Android into it. This includes lot of engineering cycles. Considering this difficult situation, Google introduces Android One program. Android Google engineers will design cost conscious hardware design that can run Android and the manufactures just needs to make it. Google also has benefits with this is that Google will be able to dictate the minimum hardware requirement and in my view a uniformity in hardware also. 

In the Google IO Demo, Google shown Micromax Android One device with dual-SIM and SD card slots, a 4.5 inch display and FM radio just priced low as 4500 INR. These phones also will get same preferential treatment as the Nexus and Google Play ranges when it comes to automatic updates.  

There is a terms Stock Android which is bit unfamiliar to many - A stock Android phone is a phone which runs Android OS without modifications. OEMs like LG, Motorola, Samsung have their own "Skinned" version of Android which is skinned to provide a differentiating UI. 

The Android One program ensures that the Automatic updates for the Stock Android on the Low end hardwares. 

It is also a talked about word that Android One is a rename for Android Silver program. 

Android One program is Android's aim for reaching 5 Billing users. During the I/O it Karbonn, Spice mobiles were also announced to be part of Android One program. 

References: 

Android Wearables

Android Wear is basically extending the Android platform to Wearables. Samsung Gear Live is compaatible with All Smart phones running on Android 4.3 Jelly bean or higher, and all favourite apps can display notifications on the Android wear. 

Moto 360 

The first that i did to know about the Moto 360 of course was to search for it. The Google result gave https://moto360.motorola.com/ 
As a developer, Signed up for it to get the details and waiting for the developer resource and more details to come in. 

The big buzz about this watch is that the UI is round unlike other smart watches. 

This is powered by the Android Wear from Google.



Samsung Gear Live

Samsung now added the Samsung GearLive to the array of its Smart wearables such as Gear Fit, Samsung Gear 2, Samsung Gear 2 Neo.

Samsung Gear Live features mainly the following 
- The display is always on. When tap on the display, it reveals more info
- Display is built on AMOLED which makes it bright, vibrant, colourful, easily visible 
- Helps to keep track of heart rate

- IP67 water resistant. 



LG G Watch


Almost same feature set as SAmsung Gear Live since this watch also powered by the Android Wear platform. 

- The display is always on. When tap on the display, it reveals more info
- Display is built on AMOLED which makes it bright, vibrant, colourful, easily visible 
- This watch doesnt seem to have a heart rate monitor
- This has got 400mAh battery 
- IP67 water and dust resistant 
- This runs on Qualcomm Snap dragon processor with 1.42GHz CPU 

The watch costs around 15K INR.


Wednesday, June 25, 2014

Android Layouts - Details

Android Layouts 

A layout defines visual structure for a user interface such as the UI for an activity or app widget. 

There are two ways we can define a layout. 

1. Declare UI in XML 
2. Instantiate Layout elements at runtime : Application can create view and ViewGroup objects (and manipulate their properties) at runtime. 

Android provides flexibility for either of these or a combination of both as well. 

A sample layout XML file is 

android:layout_width = "fill_parent"
android:layout_height="fill_parent"
android:orientation = "vertical" >
android:layout_width = "wrap_content"
android:layout_height="wrap_content"
android:text = "Hello, am a TextView"
/>
android:layout_width="wrap_content"
android:layout_height = "wrap_content"
android:text = "Hello, am a button"/>

Once after the layout is defined, we need to save it in the "/res/layout" directory.

Android system will compile each of the layout file to a View resource. The view resource should be loaded in Application code from the Activity.onCreate method. 
setContentView(R.layout.main_layout); as an example. 

In order to create views and refer from the part of the application, the common pattern is 

Tuesday, June 24, 2014

Android Data Storage - Details


There are many ways the data can be stored on an Android device. The solution which should be picked up depends on whether the data should be stored as private or should be accessible to other applications also. 

Below are the data storage options: 

1. Shared preferences
2. Internal Storage 
3. External Storage
4. SQLite Databases
5. Network Connection 

Even though the private data cannot be accessed from other application, The application itself can share the private data in a restricted manner using ContentProviders. 

Shared Preferences
This can be used to provide general framework that allows user to save and retrieve persistent key-value pairs of primitive data types. There are two ways the SharedPreference can be accessed. 

1. getSharedPreferences() - Use this method if the application needs multiple preference files identified by name, which you specify with the first parameter. 
2. getPreferences() - Use this if application needs only one preference file for the Activity. Because this is the only activity, there is no need to supply a name. 

To write the values below are the steps

1. Call Edit to get the shared preference editor - edit() method will give SharedPreferences.Editor 
2. user putString, putBoolean to add values to the shared preferences 
3. commit new values using commit() 

To read the values, application can use getBoolean, getString methods. 

Using Internal Storage
To store the data directly on internal storage which is private to the app can be done via the FileOutputStream. Below is the code to accomplish this

1. Call openFileOutput, which will return FileOutputStream
2. write to the file with write()
3. close using close() 

when calling the openFileOutput, application can specify the mode, for e.g. something like below 

FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
fos.write(string.bytes); 

fos.close(); 

Monday, June 23, 2014

Android Processes & Threads in Detail


The basics of Android system is like below

- When an application starts, it checks if any component of this application is already running. 
If Yes, Android system assigns the component to the same process and same thread of execution is used.
If No, Android system starts a new Linux process for the application with a single thread of execution. By default all components of the application run in same process and thread (called the "main" thread).   

However, an app can be configured to start different components in an application on different process and also can create own threads within a process. 

Processes
By default all application components should run in same process. Applications should not ideally change this configuration, but this can be controlled in the Application manifest file. Each component available, which are mainly , , , .  Each of these components are having the android:process attribute that can specify a process in which that component should run. Interestingly, we can also set the android:process such that components of different applications can also run in same process. However, this requires that the applications share the same Linux user ID and are signed with the same certificate. 

The element also supports and android:process attribute, to set a default value that applies to all components.  Android may shut down the process at some point when the memory is low and required by other processes that are more immediately serving the user. Application components running in the process thats killed are consquently destroyed. A process is started again when there is again work for that process to do. 

Android kill the process based on the relative importance of the app to the user. For e.g. if the activity is not visible on the screen, There are some rules Android system applies for choosing which application to be terminated. 

Process Life cycle
Android places each process into an importance hierarchy based on components running in the process and the state of the process. 
There are 5 levels of importance to processes. 

1. Foreground process
2. Visible process
3. Service Process
4. Background processes
5. Empty process 

Foreground Process
A process is declared as foreground in the below circumstances 

- It hosts an Activity that the user is currently interacting with. (the Activity's onResume has been called.) 
- It hosts a Service thats bound to the activity that the user is interacting with. 
- It hosts a service thats running in the foreground- a service's startInForeground has been called. 
- it hosts a service that's executing one of its life cycle callbacks. (onCreate(), onStart() or onDestroy())
- It hosts a BroadCastReceiver thats executing its onReceive() method 

the foreground processes are killed as last resort. - If memory is so low that they cannot all continue to run. At this point, of memory short scenario, Android system may kill the service to keep the user interface responsive, 

Visible Process
A process that doesn't have any foreground components, but still can affect what sees on the screen. A process is considered visible in below circumstances 

- It hosts and Activity that is not in the foreground, but is still visible to the user (its onPause method has been called). This may happen when a foreground activity started a dialog which will call a previous activity to get the onPause method. 
- It hosts a service that is bound to a visible activity. 

Service Process:
A process that is running a service that has been started with the startService method and does not fall into either of the two higher categories. Although these processes are not doing anything that user see directly, they are generally doing things imporatn to the user. For e.g. playing music in the background or downloading data on the network. 

Background process
These are processes those hold an activity those are no longer visible to the user. The activities onStop method has been called. Usually there are many background processes are running so, Android system will keep a LRU list to ensure the process with the activity that was most recently seen by the user is the last to be killed. IF an activity implements the lifecycle methods correctly and saves the current state, killing its process will not have a visible effect on the user experience. 

Empty process
These are processes that doesn't hold any active application components. The only reason to keep this kind of process alive is for cachine purposes.

Because a process running in a service is ranked higher than a process with background activities, an activity that initiates a long-tuning operation might do well to start a service for that operation, rather than simply create a worker thread. For e.e.g an activity thats uploading a picture to a web site should start a service to perform the upload so that the upload can continue in the background even if the user leaves the activity. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to that activity. This is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread. 

Threads 
The thread that is created when an application launched is called Main thread. This important thread is the one in charge of dispatching events to the appropriate user interface widgets, including drawing events. The main thread is the one which application is using to interact with the Android UI toolkit i.e. components from the android.widget and android.view packages.  As such the main thread is also called UIThread. 

The event handling mechanism is something like below. When user is pressing on Button, the applications UI thread dispatches the touch event to the ui widget which in turn sets its pressed state to yes and posts and invalidate request to the event queue. The UI thread dequeues the request and notifies the widget that it should redraw itself. If UI thread is hang for more than 5 seconds, the user will be presented with the Application Not responding dialog. 

Having said this, it is also to note that the Android UI toolkit is not thread safe. So, one must not manipulate the UI from a worker thread - You must do all manipulation to the user interface from the UI thread. The simple two rules thus are: 

1. Do not block the UI thread
2. Do not access the Android toolkit outside the ui thread. 

Worker Threads
If there is some operations to be done which may take longer on a UI thread, then those should be started on worker threads or otherwise called background threads. 

public void onClick(View v)
{
new Thread (new Runnable())
{
public void run ()
{
Bitmap b = loadImageFromNetwork("http://www.example.org/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}

This may seem proper, how it is not because there is a worker thread which is not a UI thread trying to access the UI and hence it becomes thread unsafe. To avoid this, Android system gives the following options

1. Activity.runOnUIThread(Runnable)
2. View.post(Runnable)
3. View.postDelayed(Runnable,long)


Using AsyncTask
AsyncTask allows one to perform asynchronous work on your user interface. It performs a blocking operation on a worker thread and then publishes the result on the UI thread. without having to handle the threads or handles ourselves. 

To make use of AsyncTask, one must subclass AsyncTask and then implement the doInBackground callback method, which runs in a pool of background threads. To update the app UI, the app should implement onPostExecute which delivers the result from background thread in doBackgrounrTask and runs in the UI Thread. The AsyncTask can be invoked by execute method on the UI thread. 

a Quick overview of AsyncTask is below 

- One can specify the type of parameters, progress values and the final value of the task, using generics 
- The method doInBackground executes automatically on a worker thread
- onPreExecute, onPostExecute, onProgressUpdate, are all invoked on the UI thread. 
- The value returned by doInBackground is sent to the onPostExecute
- One can call publishProgress at any time to invoke doInBackground to execute the onProgressUpdate method 
- One can cancel the task at anytime from any thread. 

Saturday, June 21, 2014

Movie Playing using MPMoview/ViewController

Playing the movie using the MPMoviewPlayerController is easy. 
A Movie player (of type MPMoviePlayerController) manages the playback of a movie from a file or a network stream. Playback occurs in a view owned by the movie player and takes place either fullscreen or inline. You can incorporate a movie players view into a view hierarchy owned by an app or use an MPMOviewPlayerViewControler object to manage the presentation on behalf of the app

Moview players (iOS 4.3 and later) supports wireless movie playback to Airplay-enabled hardware such as apple TV. The movie player presents a control that allows the user to choose AirPlay-enabled  hardware for playback when such hardware is in range. Starting from iOS 5.0, the AirPlay playback is enabled by default. To disable AirPlay in the app, set the allowsAirPlay property to NO. 

This class supports programmatic control of Moview playback, and user-based control via buttons supplied by the movie player. You can control most aspects of playback programmatically using the methods and properties of the MPMediaPlayback protocol, to which this class conforms. The methods and properties of that protocol let you start and stop playback, seek forward and backward through movie's content, and even change the playback rate. In addition, the controlStype property of this class lets you display a set of standard system controls that allow user to manipulate the playback. 

To facilitate creation of video bookmarks or chapter links for a long movie, MPMoviewPlayerController class defines methods for generateing thumbnail images at specific times within a movie. An app can request a single thumbnail using the thumbnailImageAtTime:timeOption: method or multiple thumbnail images using the requestThumbnaimimagesATTimes:timeopton: method


Below few lines will start the playing. 

_moviewPlayer =[ [MPMoviewPlayerController alloc]initWithContentURL:];
_moviePlayer.controlStyle = MPMoviewControlStyleDefault; 
_moviePlayer.autoPlay = YES;
[self.view addSubView:_moviePlayer.view];
[_moviePlayer setFullScreem:YES animated:YES];

We can get notifications on the status of media playing like in the notes below 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object_moviePlayer];

Below are the Movie Player Notifications available to the app

- When the movie player begins playing, is paused, or begins seeing forward or backward
- When Airplay starts or ends 
- When scaling mode of the movie changes 
- When the movies enters of exits full screen mode
- When the load state for network based movies changes 
- When meta-information about the movies itself becomes available

The supported file formats are .mov, mp4, .mpv and .3gp and using one of the following compression standards 

- H.264 baseline profile level 3.0 video, upto 640x480 at 30fps (The baseline profile doesn't support B frames) 
- MPEG-4 Part 2 video (Simple profile)

IF you use this class to play audio files, it displays a white screen with a QuickTime logo while the audio plays. For audio files, this class supports AAC-LC audio at  up to 48KHz, and MP3 (MPEG-1 audio layer 3) upto 48Khz, stereo audio. 


Friday, June 20, 2014

Touch ID Authentication

Using Local Authentication framework, applications can now request user authentication to give access to specific areas in an app. For e.g. to Payment screen

The local authentication framework currently only provide policy value LAPolicyDeviceOwnerAuthenticationWithBiometrics, which means the authentication method can be only Touch ID fingerprint biometrics 


Health Kit - Details

A large number of health monitoring devices exist from various vendors in market today those work based on Bluetooth Low Energy. For Interacting with these devices, these vendors have provided APIs. 
Taking Two Examples 
Jawbone UP
Uses REST APIs for communication 
Detailed set of APIs available at https://jawbone.com/up/developer
     Fitbit 
Uses REST APIs for communication 
Detailed set of APIs available at https://wiki.fitbit.com/display/API/Fitbit+API
     
Applications needs to make REST API calls depending on the fitness device user is having. The         complexity increases as the number of health monitoring devices increases.


Not tried to reinvent the wheel, instead helps apps to share information at a central point. 
User's health information is stored at a central secure point in device. User can see this information via health app. 
3rd party apps can now gain access to the health information for the user and provide information to the user without needing to implement specific device APIs.
Using the Health APIs, an app can register for changes so that whenever say for e.g. blood pressure become low the listener app get called back and can alert the user. 
Applications needs to activate Health Kit in project settings 
For every user data app is trying to read/write need to get permission from user 


 - Application needs to get user permission
 Execute query on the health kit store to get the details or update data


Home Kit - A first look

Smart homes are gaining grounds – Connected home concept enables user to remotely switch on/off lights, adjust home temperature via devices connected to the Home WiFi network. 
Multitude of Home Automation vendors and device and proprietary protocol 
Hard for each vendor to inter-operate, custom integration needed to bring services together between vendors 
Philips Hue Bulb example 
Provides REST based Lights API, Group API, Schedules API, Configuration API etc
Developer makes REST API calls to turn control the devices 
A number of APIs available http://developers.meethue.com/1_lightsapi.html
Belkin WeMo SDK 
SDK available at http://developers.belkin.com/wemo/sdk
Provides intefaces such as WeMoDiscoveryManager, WeMoDevice etc to control the devices

As can be seen, there is fragmentation, and it is going to grow as many players enter into market. 

Home Kit provides seamless integration between accessories that support Apple’s Home Automation Protocol and iOS devices 
Home Kit allows 3rd party apps to perform below 3 functions 
Discover accessories and add them to a persistent, cross device home configuration database
Display, edit, and act upon the data in the home configuration database
Communicate with configured accessories and services to get them to perform 
The home configuration data base is also available to Siri, so a configuration made in the app and user can invoke that via the Siri by saying “Siri, turn on the lights in the living room”
From the perspective of Home Kit, below are the entities in home automation scenario
Homes
Rooms 
Accessories
Services, Zones

The main components of Home Kit  framework are 
HMAccessoryBrowser => A network browser to discover new accessories
HMAccessory => represents a home automation accessory, such as Light bulb, Garage door
HMHome => Allows to communicate with and configure different accessories 
HMHomeManager => Manages a collection of one or more homes
HMRoom => Represents a room in home 
HMService => Represents a service provided by an accessory. Such as lightbulb, switch, 
HMServiceGroup => represents a collection of accessory services so that easier to address services as single entity   
HMTrigger => Represents an action set. 
HMZone => Represents a collection of rooms that user thinks of as a single area or zone 

Xcode 6.0 provides a simulation kit for Home Kit that will help developer to simulate the accessories and bridges


App Extension - Details


There are predefined extension points and templates for these points applications can utilize


Extension Point
Example
Today widget
Get a quick update or perform a quick task in the today view of notification center
Share
Post to a sharing website or share content with others
Action
Manipulate or view content within the context of another app
Photo Editing
Edit a photo or video within the photos app
Storage Provider
Choose a document from among the set of documents iOS app can access
Custom Keyboard
Replace the iOS system keyboard with a custom keyboard for use in all apps.
Applications can share code between extension and containing app using embedded framework.
If Extension wish to share data between containing app, then need to create an app group, and register this app group in developer portal and use the app group in containing app




An App extension lets an app to extend custom functionality and content beyond the current app and make it available to users while they are using other apps. 
A high level extension – host app – containing app integration block diagram is given below




Each template includes extension point specific implementation files and settings.

References:
https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/index.html#//apple_ref/doc/uid/TP40014214-CH20-SW1




whats new in iOS 8.0

App Extensions

Touch ID authentication

Photos framework – New APIs for working with photos, videos including iCloud assets, replacement for ALAssets framework, PhotosUI framework

AVFoundation framework – Direct control over camera focus, white balance, exposure settings. Direct control over audio, video units, ability to provide filters for simulating special effects such as speed, pitch etc

Metal – Extremely low-overhead access to A7 GPU core enabling high performance Games. Moves the state validation out of the critical path

Scene Kit – Available in iOS 8.0, provides APIs for building simple games and rich user interfaces with 3D graphics, Physics simulation engine

Sprite Kit – Adds feature to make advanced game effects. Advanced Physics simulation engine. 
Health Kit –  APIs for Managing user’s health related information 

Home Kit – APIs for communicating and controlling devices at home 

Cloud Kit – APIs for moving data between application and cloud. Provides control over when the transfer should occur.  Data can be stored in a repository that is shared by all users. Document picker allows applications to provide ui to access files outside application’s sandbox, which is a mechanism for sharing documents across apps 

Handoff – a feature that  extends user experience of continuity across devices.  Apps can make use of foundation API to participate in handoff. Each ongoing activity in an app is represented by a user activity object that contains the data needed to resume the activity on another device. When user chooses to resume an activity, the activity object is sent to another device. 

Unified Storyboard for universal apps  - allows an application to have single user interface that works well with iPhone and iPad. We no longer need to create specific story board for iPad, instead create story board for specific size and tune it for iPad/iPhone.  Defines two size classes, regular and compact.  A regular size is used for denoting a large amount of screen space such as in iPad or iPhone in portrait mode. With this definition an iPad has regular size in both landscape and portrait orientation, while iPhone has regular height and compact width in portrait, it has compact height and compact width in landscape. 

AV Kit framework – Available in iOS now, this can be used to play video instead of media player framework. 

Core image framework – can now detect rectangles,faces and QR codes in an image,

      Core Location framework -  Now apps can determine in which floor the device is in. Alternative to            significant location change, a new service called visit service, can be used by app that need             location information about interesting places visited by the user

-     iAd Framework – APIs to play preroll videos when playing the video using AVKit, APIs to look up for  effectiveness of advertisements in the app. 

Ui Kit framework changes:
Changes in push notification display behavior. Explicitly needs to set the ui display settings as opposed to specifying the type at the time of notification registration 
Local and custom notifications can include custom actions in the notification, when user tap on it, application is notified to perform corresponding action 
UIVisualEffects class provides API to introduce custom blur effects. 
Application now can take user to application related settings by openURL method.

There are changes in Game Kit, Game controller , Media Player, Sprite Kit for adding additional APIs.

There are few deprecated APIs to note 
- Registering for remote notifications now needs to be using new APIs in UIApplication class 
- UIViewController methods and properties for interface orientation. Traits and size classes replace   them. 
- UISearchDisplay controller class is replaced by UISearchController. 







Tuesday, June 17, 2014

iOS 8.0 HomeKit - In Detail

HomeKit 

Home Kit provides seamless integration between accessories that support Apple's home automation protocol and iOS devices, allowing for new advances in home automation.  By promoting a common home automation protocol and providing an API for configuring and communicating with those devices, Home Kit makes a possible market place where the app a user controls their home doesn't have to be created by the vendor who made the home automation accessories. The home automation accessories from multiple vendors can all be integrated into a single coherent whole without those vendors having to coordinate each other

Home Kit provides below capabilities to 3rd party applications 

- Discover accessories and add them to a persistent, cross device home configuration database
- Display, Edit, and act upon the data in the home configuration database 
- Communicate with configured accessories and services to get them perform actions such as turning on lights 

the Home configuration data base is not only available for 3rd party apps, but also for Siri. This allows users to give commands like "Siri, turn on the lights in the living room."

Home Kit views a Home as a collection of home automation accessories. The basic classes and hierarchies look like this. 

Home (HMHome).- Users can have multiple homes, a HMHome instance tells a single home entity 

Rooms (HMRoom) - are optional part of homes and represents individual rooms in the home. HMHome doesn't have any physical characterising, instead they are just names. For e.g. "Living room"

iOS App Extensions - In Detail

One of the very lucrative functionality with the extension is that user can provide notification centre widgets. A system area that support extension is called extension point. Each extension point provides usage policies and provides APIs that a developer can create extension in that area. 

Below are the extension points available in iOS 8.0 

Today (iOS and OS X) => Get a quick update or perform a quick task in the today view of notification centre. A Today extension is called a Widget. 
Share (iOS and OS X) => Post to a sharing website or share content with others
Action (iOS and OS X) => Manipulate or view content within the context of another app 
Photo Editing (iOS and OS X) => Edit photos or video within photos app
Finder (OS X) => Use remote storage files in OS X
Storage Provider (iOS) => Choose document from among the set of documents the current iOS app can access. 
Custom Keyboard (iOS) => Replace the iOS system keyboard with a custom keyboard for use in all apps 

it is upto the application to choose the right extension point. 

An app extension is a separate binary that executes independent of the app. One can create a new extension by defining a new target to an app. As with any target, an extension target specifies settings and files that combine to build a product within your app project. One can add multiple extensions to the target app. 
an app is called a "containing app" if it contains one or multiple extensions

When user installs the containing app, the extension also get installed

After installing an extension, user must take action to enable it. Often user can enable extension within the context of their current task. For e,g. user can edit notification centre to enable a Today extension. 

A developer should provide and icon for the app extension. Usually this will be the app icon itself. 


Below images gives overall life cycle of an app extension 



Below image gives an idea of communication between host app, extension and containing app. 

Simple Communication

Detailed communication 

Creating an Extension: 

Xcode supplies several extension templates. Once user selects and extension template, project will be added with the .appex extension file to the project. 

Cross-secting Default Extension Template
each extension template contains a property list file (that is info.plist file), a view controller class and a default user interface, all of which are defined by the extension point. The default view controller class (or principal class) can contains stubs for the extension point methods one should implement. 

the .plsit file should contain at least NSExtension key and a dictionary of keys and values each extension point specifies. For e.g. NSEXtensionPointIDentifier is a required key that is a reverse DNS name for e.g. com.livingmobile.myextension. 

some of the common keys are: 

NSExtensionAttributes: A dictionary of extension point specific attributes. such as PHSupportMediaTypes for a photo editing extension. 
NSExtensionPrincipleClass: The name of the principle extension point class. 
NSExtensionMainStoryBoard: Only for iOS. The default storyboard file for the extension, usually named as MainInterface. 

As soon as the host app issues the request (typically by calling beginRequestWithExtensionContext: method), your extension can use the extensionContext property on its principal view controller to get the context. The extension can examine the items inside the extension context and get items within it. Normally it will be good to get the extension context in the principal controllers loadView method so that one can display information in the view. To get the extension context, one can do the coding like below. 

NSExtensionContext *extContext = [self extensionContext];  

Once get the extension context, inputItems method can be invoked to get the individual extension item elements. Each ExtensionItem object contains a number of properties that describe aspects of an item such as its title, context text, attachments and user info. 

the attachments property contains an array of media data that is associated with an item. For example, in an item associated with a sharing context, the attachment property may contains a representation of webpage a use wants to share. After user work with extension using the input items, extension can give option to the user to cancel or complete the task. Depending on users choice, extension can call completeREquestREturningItems: expirationHandler:completion: optionally returning items to the host app or cancelRequestWithError:, returning an error code. We can use the NSURLSession to continue doing the potentially lengthy operation in the background such as uploading an image. 

Optimize Efficiency and Performance. 
Memory limits for running extensions are significantly lower than the memory limit imposed on a foreground app. Some extensions may have lower memory than others, for e.g. Today widgets. 

the extension doesn't own the main run loop. If the app blocks the main run loop, then it can give a bad impression in another extension or an app. 
Debugging an extension is similar to how the regular app is debugged. We can place breakpoints. It is advisable to have the instruments run on the extensions. 
An extension can be shipped only by using the containing app. 


Monday, June 16, 2014

Swift In Depth - Day IV

Classes and Objects

class NamedShape
{
var numbeOfSides:int = 0
var name : String
init (name:String)
{
self.name = name
}
func simpleDescription() -> String
{
return "this is a named shape with \(numberOfSides)"
}
}

inheritance example is below 

class Square: NamedShape
{
var sidelength:Double
var numberofsides:Int 
init (sideLength: Double, name :String)
{
self.sideLength = sideLength
super.init(name:name)
numberofsides = 4
}
func area()
{
return sideLength * sideLength
}
override func simpleDescription() -> String
{
return "A Square with \(numberofsides) side"
}
}


let test = Square(sideLength:10, name:"Square")
test.simpleDescription 

we can set getter and setters much similar to objective C 
This works much similar to the functions. An example is below 

clase EquilateralTriangle : Shape 
{
var sideLength = 0
init(sideLength: Int, name: String)
{
self.sideLength = sideLength 
super.init(sideLength:sideLength, name:name)
}

var perimeter: Double 
{
get 
{
return self.sidelength * 3 
}
set 
{
self.sidelength = newValue / 3.0 
}
}
override func simpleDescription -> String 
{
return "An equilateral triangle with sides of length \(side length)"
}
}

the newValue is an implicit name of new Value. 

Enumerations and Structures

we can user enum to create enumeration. In Swift, like how classes can have methods, enumeration also can have methods. An example is given below 

enum Rank: Int 
{
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten 
case Jack, Queen, King
func simpleDescription() -> String
{
switch self
{
case .Ace:
return "ace"
case .Jack:
return "Jack"
case .Queen:
return "Queen"
default:
return String(self.toRaw()) 
}
}
}

ket ace = Rank.ace
let aceRawValue = ace.toRaw()

one can use toRaw and fromRaw functions to convert between the raw value and the enumeration value. 

if let convertedRank = Rank.fromRaw(3)
{
let threeDescription = convertedRank.simpleDescription()
}

Structures in Swift share commonalities to its closest match, which is class. One important difference between Struct and Class is that structure is always copied when passed around while class is referenced. 

we can use keyword struct to define structure. 

struct Card
{
var rank: Rank
var suit: Suit
func simpleDescription() -> String
{
return "The \(rank.simpleDescription) of \(suite.simpleDescription)"
}
}

let threeOfSpades = Card (rank: .Three, suite: .Spades)
let threeOfSpadesDescription = threeOfSpadesDescription

Protocols And Extensions

we can use protocol to define a protocol 

protocol ExampleProtocol 
{
var simpleDescription:String{get}
mutating fund adjust()
}

class SampleClass: ExampleProtcol 
{
var simpleDescription : String = "A very simple Description"
var anotherProperty : Int = 78342
func adjust() 
{
simpleDescription += "  Now 100% adjusted"
}
}

var simpleClassObj = SimpleClass()
simpleClassObj.adjust()
let aDesc = simpleClassObj.simpleDescription


Saturday, June 14, 2014

Swift In Depth - Day III

Functions and Closures

a sample function is declared as below 

func greet(name : String, day : String) -> String 
{
return "Hello \(name) good \(day)"
}

greet ("Bob" , "morning")

we can use tuple to return multiple return values

fund getGasPrices() -> (Double, Double, Double)
{
return (3.5, 4.5, 6.7)
}

getGasPrices()

note that when there is only one return type, we don't need to have tuple brackets. 

function can also have variable argument list 

fund sumOf (numbers: Int ….) -> int 
{
var sum = 0; 
for number in numbers
{
sum += number
}
return sum
}

this function can be called like below 

sumOf()
sumOf(1,2,3)

Function can also be nested! - not sure what is the real use, but as per the explanation it says functions can be nested so that we can organise the code in a function that is long or complex. 

fund returnFifteen: () -> int 
{
var sum = 10
fun add()
{
sum+= 5
}
add()
return sum 
}

return 15

function can return another function ! 

func makeincrementer() -> (Int -> Int)
{
func incrementer (value : Int) -> Int 
{
value +=1 
}
return incrementer
}

var incremented = returnIncrementer()
incrementer(7)

A function can take another as its arguments 

func hasAnyMatches (list : int[], condition: Int -> Bool ) -> Bool 
{
var hasMatch  = false 
for value in list 
{
if condition(value)
{
hasMatch = true
}
return hasMatch
}

fund lessThanTen(value : Int ) -> Bool
{
if (value < 10)
return true
} return false

var numbers = [10,11,12]
bool match = hasAnyMatches (numbers, lessThanTen)

functions are actually a special case of closures. You can write a closure without a name by surrounding code with braces ({}). Use in to separate 
the arguments and return type from the body 

numbers.map(
{
(number: int) -> Int in 
let result = 3 * number 
return result
}

)

Friday, June 13, 2014

Swift In Depth - Day II

Optional strings can be represented by var optionalString : String ? = "Hello"
? after the type indicates that the value is optional. if the string contains no value, it will be set to nil 

in the below statement, if the value for optionalName is present, it is assigned to the name variable and the conditional block will be executed

if let name = optionalName 
{
greeting = "Hello \(name)"
}

Switches will now support any kind of data type. they are not limited to integers. 

let vegetable = "red pepper"
switch vegetable
{
case "celery": 
let vegetableComment = "Add some raisins"
case "cucumber", "watercress":
let vegetableComment = "That would make a good sandwich"
case let x where x.hasPrefix("pepper")
let vegetableComment = "It is a spicy \(x)?"
default:
let vegetableComment = "every thing tastes good in soup" 
}

unlike earlier case, if any of the switch statement matches, it goes inside and exists after this, we don't need to have a break by default. 

for looping we need to use for-in statements 

let interestingNumbers = [
"Prime" : [2,3,5,7,11,13],
"Fibanocci" : [1,1,2,3,5,8],
"Square" : [1,4,9,16,25],


int largest = 0
for (kind, numbers) in interestingNumbers
{
for (number in numbers)
{
if (number > largest)
{
largest  = number
}
}
}

var n = 2
while n < 100 
{
n = n *2 
}

we can keep an index in a loop using a .. operator ! 

var firstLoop = 0
for i  in 0..3 
{
firstLoop += i
}
firstLoop 

var secondLoop = 3
for var i = 0; i < 3; i++
{
secondLoop +=3 
}

secondLoop

Thursday, June 12, 2014

Swift In Depth - Day I

The convention of printing a "Hello World" message is just one line in swift which is below 

println("hello world")

One difference to notice is that there is no semi colon. Also in swift line of code is a complete program! . one need not import a separate library for functionality like input/output or string handling. Code written at a global scope is considered as entry point for the program. so we don't need main also! 

We need to use let to make a constant and var to make a variable. The value of a constant doesn't need to be known at compile time. but we can assign the value only once. 

var myvariable = 43
myvariable = 45
let myconstant = 50

Providing the value at the initial time will let the compiler infer the type of the variable. However it is also possible to specify the type as part of the declaration 
for e.g. let explicitDouble: Double = 70 will tell that the constant explicitDouble is a Double type. 

let apples = 3
let oranges = 4
let appleSummary = "I have (apples) apples"
let fruitSummary = "I have (apples+oranges) pieces of fruit"

arrays and dictionaries use brackets. e.g. like below 

var animals = ["cat","mat","rat"]
animals[1] = "pussy cat"

var occupations = [ 
"steve" : "manager", 
"mary" : "speaker",
"taylor" : "cricketer",
]

occupations["marshal"]  = "guide"

Empty array and dictionary can be created in this following way:

let emptyArray = String[] ()
let emptyDict = Dictionary ()

Control Flow 

Control flow is using switch or if, and loop is using for in, for, while and do-while 
let individualScores = [75, 85, 103, 87, 12]
var teamscore = 0 
for score in individualScores 
{
if (score > 50)
{
teamScrore += 3
}
else 
{
teamscore += 1
}
}


in a condition statement, the expression must be a boolean variable. it cannot have if (score), instead, it should be if (score == 0 )