In-Out Parameters | Swift 3

inout keyword is a powerful alternative to tuples for Swift and one thing to make a mistake.

PFB- Some notes worth considering
  1. When the function is called, the value of the argument is copied. (also known as copy-in copy-out or call by value result)
  2. In the body of the function, the copy is modified.
  3. When the function returns, the copy’s value is assigned to the original argument.
  4. In-out parameters cannot have default values.
  5. Variadic parameters cannot be marked as inout.
  6. We must use the ampersand "&" when passing arguments.

/// inout

func check ( string: inout String) {
    string = "Innova"

var string = "hello"

check(string: &string)

Variadic Functions | Go by Example - Swift 3.0

Variadic functions can be called with any number of trailing arguments. Same like print(...) for Swift. Can be used with define type e.g. "String, Int.." or Any protocol.

/// variadic
func variadic (any: Any...) {
    if any.isEmpty {

    for val in any {


variadic(any: "hello", "world", 2017, 2.0)

SieveSort Algorithm | Swift 3.0

SieveSort, based on the technique of divide-and-conquer, that takes time O(n2) in the worst-case. Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
/// sieve algo
func sieve (numbers: [Int]) -> [Int] {

    if numbers.isEmpty {
        return []
    let p = numbers[0]
    return [p] + sieve(numbers: numbers[1.. 0


sieve(numbers: [2,3,4,5,6,7,8,9])

UIActionSheet in iOS 8

UIActionSheet and UIActionSheetDelegate is deprecated in iOS 8. To create and manage action sheets in iOS 8 / later, we need to use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet because if we have used the same in our previous code it will simply not appear in iOS 8. Don't panic! It won't make a crash ;)
PFB - A quick adaptation for UIActionSheet/Delegate

UIView controls greyed out in iOS7

When opening and closing sheets and popovers in iOS7 the ui-controls like UISegmentedControl, UIProgressView, etc.
Its in the Apple's native app as well, where the bar button items become greyed, or conversely, they no longer turn to grey once a popover/viewcontroller shows up.

Its an open bug in iOS7, for quick fix we can manually set tintAdjustmentMode property of the effected UIView to UIViewTintAdjustmentModeNormal, e.g;
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithFrame:CGRectMake(x, y, width, height)];
segmentedControl.tintAdjustmentMode = UIViewTintAdjustmentModeNormal;

NOTE: This will prevent the color toggling in any case, i.e; there will be no effect of dimming when opening Popover/Sheet/ViewController

Handoff in iOS8

Handoff is all about making you work across all devices within proximity range. It uses BTLE (Bluetooth low energy or Bluetooth LE ) and iCloud account to pair devices. After pairing in iOS it display the current app icon in left corner of the lock screen, left side of home screen in multitasking switcher screen, On Mac it shows in right part of the dock and command + tab menu

Handoff supports live streaming between apps in two devices. Handoff works in between websites and apps as well.

Fundamental unit of handoff is an Activity (NSUserActivity). When we create an Activity it automatically brodcasts and shows up in paired devices. When user selects the Activity (i.e; select the app) the host is informed and asked for the detaled information, after that host sends the detailed package and the app get launched.

All applications from the same developer can exchange activities this is based on the team identifier. Applications don't have to claim;
  • the same activity type they create
  • any activity types, but can still create them
This is helpful when there are multiple apps in iOS for an app in OSX

Creating, Updating and Continuing Activity is supported by AppKit and UIKit, i.e; UIDocument, UIResponder now have a NSUserActivity property. In UIDocument based apps the activity is set in .plist and will be managed by OS itself. In UIResponder, when the app is in focus UIKit walks the view hierarchy and check for the Activity. Every time user focus the Activity it evokes the becomeCurrent method and invalidate when it finished. To manage user, Activity have userInfo property for minimal ammont of information. It is a dictonary and can store NSArray, NSData, NSDate, NSDictonary, NSNull, NSNumber, NSSet, NSString, NSUUID, NSURL..

UIApplicationDelegate have new method (i.e; application:continueUserActivity:restorationHandler:) which tells the delegate that the data for continuing an activity is available. This method have a optional block, restorationHandler which executes if your app creates or fetches objects to perform the task it must be called from the app’s main thread. restorationHandler has no return value and take restorableObjects as param which is an array of UIResponder or UIDocument objects representing objects you created or fetched in order to perform the operation.

When continued from another device NSUserActivityDelegate call userActivityWasContinued: which notifies the delegate that the user activity was continued on another device. This will helpful when more then two devices are paired and Handoff on the same app.

Extensions in iOS - Keynote

  1. Not all but most of the APIs are available for extesions
  2. Extensions have separate container for them which means they act like a saperate app for there parent app
  3. Extensions don't have access to their parent app data but can opt into data sharing
  4. Apps and Extensions can use a shared container/storage area which can be accessed at same time with the help of;
    • NSFileCordination - provides general syns strategy for app and extension
    • CoreData
    • sqilite
    • NSUserDefaults - with a shared suite name
    • Shared Keychains - for an app group
  5. Once user approve the Privacy access (e.g; Photos, Location..) to an app all its extensions don't need to ask saperately
  6. Extensions are stateless that means they are killed aggressively

Extensions configuration keys in .plist
  • NSExtension - A dictionary of keys and values that describe an app extension
    • NSExtensionPointIdentifier - Extension point’s reverse DNS name PFB
    • NSExtensionPrincipalClass - The name of the principal view controller class created by the template
    • NSExtensionAttributes - A dictionary of extension point–specific attributes that specify aspects of an app extension
      • further configuration based on extension kind

Values for the NSExtensionPointIdentifier key based on extension type;
  • Action Extension -
  • Custom Keyboard Extension -
  • Document Picker Extension -
  • File Provider Extension -
  • Finder Sync Extension -
  • Photo Editing Extension -
  • Share Extension -
  • Today Extension -

View Controllers in iOS 8 - A quick review

High level changes

Traits replaced UIViewController methods and properties for interface orientation PFB
UIAlertController replaced UIActionSheet and UIAlertView
UISearchController replaced UISearchDisplayController
UIUserNotificationSettings replaced UIApplication methods and properties for registering notifications, supported register the types of alerts local or push notifications with some custom actions apart from remote notifications
UISplitViewController supported on iPhone as well as iPad with new collapsed property PFB
UINavigationController added options to condensing and hiding PFB
UIPresentationController provides advanced view and transition management for presented view controllers PFB
UIPrinterPickerController view controller-based way to display a list of printers
UIPopoverPresentationController manages the display of content in a popover

Methods for showing view controller are changed to;
  1. showViewController: sender: - replacement for all showing view controller methods
  2. showDetailViewController: sender: - its implimented by split view controller
and these are implemented by all custom view controllers as well.

Previously we used to differentiate orientation with UIInterfaceOrientation and UIUserInterfaceIdiom, in iOS 8 insteed of this there is a new concept of Size Classes. Size Classes have four different variations based on Vertical, Horizontal, Regular and Compact ie;
  1. Horizontal Regular - iPad landscape, iPhone portrait
  2. Horizontal Compact - iPhone landscape
  3. Vertical Regular - iPad portrait
  4. Vertical Compact - iPhone portrait, iPhone landscape
An iPad have regular size classes only.

Traits and Trait collections

Traits are the bunch of properties that we can use to determine how the layout of your application should change as its environment changes. It is consist of following properties;
  • Horizontal size class - Regular / Compact
  • Vertical size class - Regular / Compact
  • User interface idiom - iPhone / iPad / iPod Touch
  • Display scale - 1.0 / 2.0
These properties can be "Unspecified" in such case when a UIView is not in the view hierarchy or we have specified a custom Trait Collection. We can also customize the Trait Collection of a child view with Appearance Proxy. Trait Collections (a.k.a UITraitCollection) vended from trait container have both a horizontal and vertical size class trait, it used to describe a collection of traits assigned to an object.

All these Traits and its values are wrapped in a container i.e; Trait Collections. Trait Environments of a child are inherited from its parent because of this we can access Trait Environments till root from any child. We can get change notification with traitCollectionDidChange: method and override it in UIView and UIViewController subclasses to react to a trait change.

Trait Environments (a.k.a UITraitEnvironment) is a protocol which provides access to a view collection’s traits (object.traitCollection) and a way to track changes in the trait collection ([object traitCollectionDidChange:]). Its confirmed by most of the objects in view hierarchy i.e; Screen > Window > View Controller(s) > View(s) UIViewController adopts traits and the new sizing techniques for adjusting the view controller’s content. Traits are consist of Size Class, Display Scale and Idiom for a particular view object. Size Class coarsely defines the space available and categorizes available space horizontally and vertically.

Trait Collection are also implemented in UIImage so that we can provide image for any size rather then 1x and 2x versions using Assets Catalog. UIImage view automatically picks the write image based on its Trait Collection, this will be usefull in such case when we need saperate image with respect to varity of size classes.

We can also add multiple Trait Collection with the help of traitCollectionWithTraitsFromCollections:, on addition the unspecified Traits are filled by the specified and for multiple specified Traits, the last one will be picked.

UIViewController also have new methods which helps Parent View Controller to override the traits for a child, i.e;
  • -(void)setOverrideTraitCollection: forChildViewController:
  • -(UITraitCollection *)overrideTraitCollectionForChildViewController:

Split View Controller

UISplitViewController is by default collapsed for horizontally compact container (e.g; iPhone, iPod Touch..) otherwise they are expended, the same can be changed further. We can also adjust the % width of both partitions a UISplitViewController.

Good to know: We can also track split view controller expand/collapse with UIViewControllerShowDetailTargetDidChangeNotification in NSNotificationCenter

Navigation Controller Condensing

There are several awaited features are implimented in UINavigationController, auto and manual toggling nav bar i.e;
  • navController.hideBarOnTap - to enable auto toggle hide/show on tapping
  • navController.condensesBarOnSwiped - to enable safari like auto condensing bars
  • navController.hidesBarWhenVerticallyCompact - to enable auto hides bar for vertically mode
  • navController.condensesBarsWhenKeyboardAppears - to enable auto condensing bars when keyboard appears
  • navController.navugationBarCondensed - to manually toggle nav bar

Presentation Controllers

Presentation Controller enhance the exesting API for creating custom presentation, all presentation styles now have an associated Presentation Controller with them. Some new presentation styles are introduced as well, i.e;
  • UIModelPresentationOverFullscreen - shown like an overlay which means it don't remove the presenting view controller
  • UIModelPresentationOverCurrentContext - cover upon the presenting view controller only
  • UIModelPresentationPopover - it is more like a popover itself
Now most of the iPad-only styles are avilable in iPhone as well, some of them are in full screen mode (for iPhone) by default but configurable to be non-full screen.

Presentation Controllers can easily adapt to size class change. We can use Adaptive Presentations (a.k.a UIAdaptivePresentationControllerDelegate) to track the presentation orientation change. We can create custom presentation controllers which will adapt if shouldPresentInFullscreen returns YES.

Transition Coordinators (a.k.a UIViewControllerTransitionCoordinator) are part of the UIViewController adaptive UI story. During an active view controller transition, use Transition Coordinator to respond to user cancelation of the transition to run a custom animation or register a completion handler. UIContentContainer can help you to adapt the contents of your view controllers to size and trait changes. New methods are added to it to provide support for Trait, i.e;
  1. -(void)willTransictionToTraitCollection:withTransitionCoordinator: -
  2. -(void)viewWillTransitionToSize:withTransitionCoordinator: -

UIScreen is now interface oriented, which means;
  • -[UIScreen bounds] are interface-oriented
  • -[UIScreen applicationFrame] are interface-oriented
  • Status bar frame notification are interface-oriented
  • Keyboard frame notification are interface-oriented
To still work in fixed cordinate system we can use protocol UICordinateSpace

New in Interface Builder

  • We can use same Storyboard/XIB for any screen size of all iOS devices like iPhone4S, iPhone5, iPad..
  • We can deploy backwards to iOS 6 and iOS 7
  • We can preview devices, orientation and OS versions. Go to Jump Bar > Preview Assistance > Chose plus button from bottom to select device and desired orientation
  • We can to use Auto Layout to design flexible UI
  • We can remove or add unique Auto Layout constraints for each screen size
  • We can use Assets Catalog for images to use different versions of same image based on size
  • We can override subviews for specific size class

Home Kit Overview

HomeKit allows your app to communicate with and control connected accessories that support Apple's Home Automation Protocol in a user’s home. To use HomeKit with your iOS apps just switch-on HomeKit in the project editor capabilities panel. HomeKit have a common/central accessories configuration database with read/write access to all apps.
We can find and add an new Accessory with Accessory Browser (a.k.a HMAccessoryBrowser). If found we can add the new Accessory to the Home, after that we can assign the same to a Room in that home.
We can use HomeKit Accessory Simulator (which act as a real accessory) to test custom made accessories in iOS Simulator. We can open it from Xcode > Open Developer Tool > Home Kit Accessory Simulator. Every accessory come with a setup code to associate it with a Home via HomeKit

HomeKit is managed by the Home Manager (a.k.a HMHomeManager), which provides a pointer to the common database, allowes to manage/create homes and notify the changes. Home (a.k.a HMHome) should have a unque name because its being used by Siri for commands. Home have Roomes (a.k.a HMRoom) in it, (which is also uniquely named for that perticular Home) and Rooms have accessories in them. An Accessory (a.k.a HMAccessory) corresponds to a phycical device (its also uniquely named in its room).
We can also group the Rooms in Zones (a.k.a HMZones), its completely optional and uniquely named with a home. A room can be in any number of zones. Its recognized by Siri.

Basic steps to setup an accessory are;
  1. Create a home
  2. Add rooms to the home
  3. Add accessories
Accessories functionality and characteristics (like temperature, illumination..) are managed by the Services (a.k.a HMService). A Service can be exposed with an unique name/type so that user can trigger the same with Siri. Characteristic (a.k.a HMCharacteristic) of a Services can be read-only, read-write or write-only.
Alike Zones, We can also group Services with HMServiceGroup
We can create Action Sets (a.k.a HMActionSet), which is a collection of Actions (a.k.a HMCharacteristicWriteAction) that are executed together. Its also uniquely named and recognized by Siri.
We can also create timed Triggers (a.k.a HMTimerTrigger) to execute an Action Set that will be fired on an specific date and time or repeatedly. They are managed by iOS itself and executed in background.

There are many-many delegate methods are exposed by the HomeKit to track each and every change caused by other apps, system or accessories state change. e.g;
  1. HMAccessoryBrowserDelegate - to notify a new accessories found or removed
  2. HMAccessoryDelegate - to notify state change of accessories
  3. HMHomeDelegate - to notify configuration changes in the home
  4. HMHomeManagerDelegate - to track changes to a collection of homes

CloudKit in conciseness

CloudKit is an API to interact with iCloud Drive, iCloud CoreData and iCloud Photo Library. Its supported on both iOS and OS X. It needs an iCloud account for read/write access because it don't have any persistent memory of its own. CloudKit supports Public and Private databases with both Structured and Bulk data. Key components of the CloudKit are;
  1. Containers encapsulates content associated with an app, including both public and private data. It coordinates all interactions between your app and the server. Its exposed as CKContainer object. It can be managed by WWDR portal. Its namespace should be unique like your app identifier.
  2. Databases - is a channel to access the public and private data of an app container. Every app have two kinda databases, ie;
    • Public Database - It have shared data with read-only anonymous access with data saved on developer quota (i.e; 1 Petabyte)
    • Private Database - It have current user's data so it needs an iCloud account for writing and use current user's quota which depends on users iCloud plan
  3. Records - is a dictionary of key-value pairs that you use to fetch and save the structured data with just-in-time schema. It can also have a metadata with change tag associated with it. It can save NSString, NSNumber, NSData, NSDate, CLLocation, CKRefrence, CKAsset and An array of all of them
  4. Record Zones - is a virtual grouping of Records, it can be custom.
  5. Record Identifiers - uniquely identifies a custom created record zone in a database. They also represents the location of a record.
  6. References - are the relationship(can be many-to-one) between objects. It is allowed to create circular owning references for a set of records. It supports cascade deletes so its recommended to do Back References.
  7. Assets - are large files associated with records. Alike Records we can use Asset objects to incorporate huge external files such as images, sound files, video files. Assets are saved as files on iCloud and owned by a Record.
To enable the CloudKit in our project we just need to enable the Capabilites -> iCloud -> CloudKit from Project Settings, It expose two kinda APIs, i.e;
  1. Operational - in-depth access to CloudKit
  2. Conventional - peaceful for general usage

As other conventional DBs CloudKit also use the queries to fetch data, i.e. CKQuery. Its consist of RecordType, NSPredicate and NSSortDescriptors.

To save devices resources we can also run our query asynchronously on iCloud server, by using CKSubscription. Its consist of RecordType, NSPredicate and Push (via Apple Push Service)

CloudKit don't expose user's account details (like email, user name,..) for the sake of privacy. For user mapping iCloud expose stable UUID based on a user and an app Container. An app can ask for permission to the user details. An app can also ask for permission to the user's contacts (have the iCloud account) to enable sharing capabilities.

App can also use iCloud Key-Value Store for storing (up to 1 MB) configuration data, preferences, and small amounts of app-related data.

WebKit API in a nutshell

WebKit API (for a quick recap, WebKit is a layout and rendring engine for web that's used by Safari, Dashboard, Mail, and many other Apple applications) replaces the traditional UIWebView with WKWebView with lots of powerful features i.e;
  • Responsive scrolling with 60 frames/sec
  • Power of JS Nitro engion (the engine formerly known as SquirrelFish)
  • Built-in multi gesture
  • App-Web Page communication
  • Automatic Multi-process Architecture - means web view have saperate process alike the app itself
  • Energy efficient
  • It is configurable with WKWebViewConfiguration class
Some basic WKWebView features;
  • Its actions and navigation flow can be easily configurable
  • Its properties can be easily accessable (with KVO as well), e.g; Active page title, URL, estimated progress, etc.
  • With WKNavigationDelegate - its actions can be easily managed same like UIWebView, i.e; app will be notified for url will/did change and page did finish loading
  • WKNavigationDelegate can also tell about, navigation type, source frame, destination frame, etc. in a WKNavigationAction object
  • WKNavigationResponse is the response object, it also have some useful properties as well
  • Configurable Navigation Gestures for back and forward options
Customizing web page content within WKWebView can be done by WKUserContentController which is part of WKWebViewConfiguration. The same can be done by two ways, i.e;
  1. User Sctipts - to take some JS and inject it into the web page, it can executed both start and end of dom loading
  2. Script Messages - are the messages that user scripts send back to the app, it can carry JSON as well
    • To recive Script Messages we need to register WKScriptMessageHandler protocol and messages can be sent by a simple JS call, i.e; window.webkit.messageHandlers.{NAME}.postMessage()
    • The recived message is an object of WKScriptMessage with contains; body, webView(reference to the sender web view) and name
    • Web page itself can post the Script Message if their JS are coded to do so
    • We need to be aware of security risks because any JS can call a Script Message

Share Extensions - Recap

Share Extensions are used to share Audio, Video, Photos, Comments, Links etc, from supported app. In case of web content an app can specify the two types of input i.e; Web URL and Web Page. Web URL is simply the current URL as a string but the Web Page is full HTML of the shared page based on the JS provided by the host app.

Basic requirments to register an app for sharing;
  1. Display Name - CFBundleDisplayName
  2. Activition Rules - Inform the iOS about what kind to data they support to share, based on the same iOS will select the app to be shown in sharing menu. App should have appropriate information in ".plist" file @ NSExtension -> NSExtensionAttributes -> NSExtensionActivationRule. There are two ways to supply this information, i.e;
    • Predicates - A complex or simple predicate with supported types, in this case NSExtensionActivationRule will be string type
    • Condensed - A simple list of supported sharing types, in this case NSExtensionActivationRule will be dictionary type
    An app can specify the ammount of data it can take at a time in the activation rules.
  3. ViewController - App need to provide a ViewController subclassed with SLComposeServiceViewController which will be displayed at the time of sharing

NOTE:For Share Extensions we should use NSURLSession to perform server data transfears the reason being your extension does not live beyond its presentation.

Basic settings of SLComposeServiceViewController;
  1. PhotoBlogCharacterLimit - for max length of share message size
  2. PhotoBlogTmageDataMaxSize - for max image size
  3. - (BOOL)isContentValid method to return the runtime validation result, return false will disable the Post button
  4. - (NSArray *)configurationItems Returns configuration items to display in the compose view.
  5. AudiencePickerViewController/Delegate need to be implimented for privacy setting (Optional)

Today Extensions - Widgets at a glance

Extensions in iOS are delivered as a part of your app in Extension Container. They are purpose built binaries which can be accessed via Apple framework code. They don't provide app to app inter-process communication.

Extension Points are the frameworks exposed to the both Widget and its App to provide an information exchange architecture. Extensions can only communicate with there hosting app.
Today Extensions also known as Notification Center Extensions or Widgets are view controllers (it follows all lifecycle methods).

From performance perspective;
  • Cache fetched data
  • Load cached data for seamless transitions
  • Should complete heavy operations in background

From layout perspective;
  • The notification Center itself set frames of the base view
  • Its recommended to use Auto-layout
  • We can resize the widget height based on our needs
  • We can manage the Animations and Transitions while changing view, they will work in parallel of system transitions
  • Widget can receive the size change notifications and perform required changes based on that

Basic steps to create a new widget for your app;
  1. In your existing app, "Add a new target"
  2. There is a new "Application Extension" option in XCode 6+
  3. Select "Today Extension"
  4. Create a "UIViewController" attached to storyboard
  5. Code the content of your view controller just like you code it for your app, this might be any kinda listing or detailed info, whatsoever..
  6. We can provide widget height in "-(void)awakeFromNib" by setting [self setPreferredContentSize:---]
  7. We can use "-(void)widgetPerformUpdateWithCompletionHandler:" to get notified for our widget update and perform essential data update. NCWidgetProviding provides mechanism to get informed about widget.
  8. Optionally or Based on app requirement, we can add a link in the widget to our app so that user can see detailed information
  9. We can access the host app with [self extensionContext], by using the same we can perform [.. openURL] and open the app with its registered URL scheme (e.g; sampleapp://)

Health Kit APIs at a glance

Health Kit APIs are designed to work with existing Health Apps, with this API app can share statistical analysis (e.g; graphs, trends..), user information etc.. and user can check it from iOS "Health" app
With Health Kit API we can create, save and ask for users health and fitness related data which is centrally managed by iOS "Health" app. This can be used for surfacing data from other health app and read/write your own data. There are some basics we need to know to get started with the same;
  1. HKUnit - It represents a particular unit that can be accessed in any conversion (eg; Kg, Lb, Gram,..)
  2. HKQuantity - A double value related to a HKUnit. Note: there will be an excecption if you convert different units (e.g; Kg -> Liter), you can ask for compatibility (isCompatiableWithUnit:) if you are not sure
  3. HKObjectType - It represents different kind of data that we can store in HealthKit (e.g; Steps, Calories, BMI, Blood Pressure, etc..), it is a superclass for all Health Kit data types, i.e;
    • HKCharactersticType - fixed user info like blood type, date of birth, gender
    • HKSampleType - variable user info, it is consist of;
      • HKQuantityType - (for Steps, Calories, etc.)
      • HKCategoryType - used to categorize HKQuantityType, its paired with corresponding enum
    HKObjectType is immutable and its properties are read-only.
We need HKHealthStore to save data, it is kinda link to the database. It will let you save objects and query for data. Usage of multiple HKHealthStore is not recommended. Its easy to ask for HKCharactersticType info of user because HKHealthStore have direct methods for the same, but for complex info there are queries, i.e;
  1. HKQuery - we can use predicates to search for our needs.
  2. HKObserverQuery - watches for changes in the database, it will called each and every something changed in database related to your query. It supports background delivery.
  3. HKAnchoredObjectQuery - it will help in paging of data, it is consist of Anchor and Limit. Anchor is a simple starting point. If we set Anchor to zero if will return all data with limit, for no limit we can use constant "HKObjectQueryNoLimit". Complition handler will have a new Anchor which we can use in our next query
Once we create a query we can execute it with the help of HKHealthStore, it have method two methods "-(void)executeQuery:(HKQuery *)query;" and "-(void)stopQuery:(HKQuery *)query;". We can call a query only once because its callbacks are invalidated once query is stopped. We only need to stop HKObserverQuery because other query will execute callback method only one time.

We can use HKStatics to get required quantity data from the query output, we can ask statictics for all kinda data or a particular HKSource data. There are two kinda quantity data, i.e;
  1. Discrete - Min, Max, Average (e.g; user's average weight in a week)
  2. Cumulative - Sum (e.g; sum of steps taken in a perticular interval)
We can filter statictics with the help of HKStatisticsQuery, it takes options as HKStatisticsOptions and returns HKStatistics object. List of HKStatistics objects can be kept in HKStatisticsCollection, which can be further used based on time intervals. HKStatisticsCollectionQuery is used to fetch usefull info from HKStatisticsCollection, it is consist of Statictics options, Anchor data and interval.

Good to know

  1. We need to activate HealthKit in your project settings
  2. We need to ask for authorization to read/write health data saparately for each and every type of info
  3. Always check of access authorization because user can manage anytime from outside the app
  4. An app can't get status for read access to the user info because of Apple's Privacy Policy
  5. We need to localize the units ourself, we can do so with the help of NSMassFormatter, NSLengthFormatter and NSEnergyFormatter

Sample App

Fit Store and Retrieve Health Kit Data - Sample App is avilabe at Apple developer portal you can download it from here.

New in Cocoa Touch

With iOS 8 Apple is now providing easy access to there native visual effects (i.e; Condensing Bars, UIBlurEffects, UIVibrancyEffect, etc.)
Now notifications will work only for UI, that means if user don't approve the Push Notification the app can still get payload (which can be upto 1kb insteed of 256b). Notification can have action associated with them as well, like a Reply button. Notification can be configured based on user location as well.

iOS 8 is more about adaptivity in how we design our apps architecture, with its new resizable iOS Simulator and all new features, i.e;
  1. Adaptive View Controllers i.e;
    • Adaptive Layout (i.e; Orientation, size and margins). Margins adaptivity can be achived by Layout Guide. Orientation, size adaptivity can be achived by Trait Collection, it is for everything you need to know about layout. Trait Collection is based on Size classes, Display scale and User interface idiom.
    • Adaptive View Controller Hierarchies (i.e; Unifyed Code). Split View Controller will be auto managed as Navigation View Controller for iPad and iPhone with enhanced customizability.
  2. Adaptive Presentation (i.e; Popovers, Search results, Alerts etc.) e.g; UIAlertController will replace UIAlertView in iPhone and UIActionSheet in iPad
  3. Adaptive Text and Tables (i.e; They have also introduces some long awaited features like auto height for table row)
  4. App Extensions

Internationalisation and Localisation in iOS8+

Locale is made up of "Language" + [optional script] + "Region" + [optional keywords]. Locale settings are based on user preferences and not a reliable source for other operations, e.g; Getting user's "Physical Location"/"Country of residence" which should be obtained by CoreLocation API.

Locale settings are auto imposed by iOS itself we don't need to do additional coding for the same until or unless we are't going off-track. For some special cases like if we want to get localized data from server you can access Locale setting to do so. We can also use the same logic which are being used by NSBundle by +[NSBundle preferredLocalizationsFromArray:(NSArray *)localizationsArray]

NSLinguisticTagger can be used for Document linguistice content.

We can get Locale change notification with NSCurrentLocaleDidChangeNotification and impliment it on the go. There are two kinda prefrences for iOS users to chose localisation based on which App and web sites use the language they support, i.e;
  1. Preferred languages - it determines;
    • NSBundle
    • NSLocalizedString
    • HTTP header "Accept-Language" in WebKit
  2. Local/Regional preferences - it determines;
    • NSLocale properties
    • Formatter behaviour
    • NSCalendar

PFB - list of major changes in iOS8+ localisation

  1. New localisation
    • Hindi
    • Indian English
    • Canadian French
    • Hong Kong Chinese
  2. New keyboards
    • Bengali
    • Marathi
    • Urdu
    • Indian English
    • Filipino
    • Slovenian
  3. New fonts for various languages
  4. Language and region settings
    • Specify primary language
    • Specify preferred language order
    • Localisation into other non-native languages
    • Specify region format language independently
  5. Lunar calendar support with two new Islamic calendars
  6. String encoding detection/conversion for unknown source file with lossy and non-lossy both
  7. New formatters with formatting context support, i.e;
    • NSDateComponentsFormatter - Display duration of time in various languages
    • NSDateIntervalFormatter - Display time-intervals in various languages
    • NSEnergyFormatter - Display energy units (e.g; Calories) in various languages
    • NSLengthFormatter - Display length (e.g; Miles, KM..) in various languages
    • NSMassFormatter - Display mass (e.g; Pound, Kg..) in various languages
Good to knows; Because of multiple keyboard support by iOS8+ we need to manage views based on the keyboard size change.

New features introduced in Apple App Store

  1. Related searches
  2. Tending Searches
  3. Editor choice badge in App details
  4. Preview movie for app
  5. App bundle where developers can bundle same kinda apps and can sale the bundle saperately
  6. New iTunes Connect dashboard
  7. iTunes Analytics for Purchased, Visited, Active Users.. More like Google Play Store
  8. Apple TestFlight integrated in the iTunes store for Beta Releases of the App
  9. Now we can distribute app up-to 1000 users for testing with the help of Apple TestFlight
  10. Apple TestFlight can also collect and manage the Crash Reports as well

XCode 6 features highlights

  1. Single storyboard for all screen sizes iOS devices
  2. Size classes for Adaptive UI, Its a nice take. With the help of size classes we can configure screen elements for multiple screen sizes
  3. Preview Assistant to check output on multiple screen sizes
  4. We can use Playground to check code snippets
  5. Launch images can be auto generated
  6. Storyboards can be used for mac apps as well
  7. Asset Catalog supports more types vectors as well
  8. Search enhanced
  9. Designing with custom fonts made easy
  10. Localisation enhanced and automated (+XLIFF Support), No need to use string files from now.
  11. Pseudo localisation can be used to save localisation cost (see if it works for you)
  12. Runtime localisation check support
  13. Custom controls can be edited live on interface builder with the help of IBInspectable and IBDesignable
  14. Debugging have feature to backtrace the blocks as well
  15. Debugging and Profiling for Games enhanced
  16. Support for Async Testing with XCTestExpectation
  17. Performance testing with detailed information and control
  18. Instruments are redesigned
  19. New Profile Guided Optimisation to optimize your code for runtime performance
  20. Xcode Bots to manage responsibility for bugs
  21. With View Debugging feature we can inspect element on the go, #RIP Revel App
  22. Debug gauges, to provide at-a-glance information about Network Activity, File Activity and iCloud usage while debugging
  23. iOS Simulator got new custom screen size configurations and it allow you to keep data and configuration settings grouped together.

APIs introduced in iOS 8

iOS 7 was something big for its designers and now its time for developers. Yes, iOS 8 is really huge for developers with all new Swift, Unified Storyboards, Handoff and so forth.
Some new features of iOS can surely change the way we achieve our business logic, like CloudKit and Cordova can do really amazing work together. With App Extensions now its easy to interact with iOS, Some interesting things we can do with App Extensions:
  1. Sharing for most of data e.g;
    • Audio
    • Video
    • Photos
    • Comments
    • Links
  2. Actions to Transform data
  3. Photo editing in native iOS App
  4. Safari extensions to access and manipulate DOM
  5. Interactive notification center widgets
  6. Document providers to access additional storage
  7. Third party keyboards with more languages and input methods

PFB- A high level idea of new APIs introduced in iOS8;
1) CloudKit
From iOS8+, user can access there files from third party document providers within an app, CloudKit provides APIs to code the same. It is a network depended Cloud access framework for shared cloud storage. Its classes can't be subclassed. Its synchronous and for asynchronous transfers it relies on NSOperation/GCD. Good to know things before starting with iCloud Drive;
  • User can access shared files from Finder in Mac
  • We need to use UIDocumentPicker to access iCloud Drive files in iOS because there is no shared storage app in iOS for it
  • We can manage Records, Relationships and Queries with CKRecord framework and Assets/Larg data blobs with the help of CKAsset framework
  • We can use CKSubscription framework to get notified in case of change in cloud with a cute puch notification
  • We can access the cloud with the help of Developer Portal
  • No need to create user accounts as we can use user's iCloud Account
  • Storage is free, but Apple have reserved the access rights for it to prevent misusage
2) CoreAuthentication
Device owner authentication with/without biometrics (Touch ID - iPhone5S+)
3) HealthKit
Access users health related data managed by Apple Health, i.e; Sex, BloodType etc. Access health accessories sensors reports i.e; Body temperature, Heart rate etc.
4) HomeKit
It provide support to work with Apple's Home Automation Protocol. It will help you Discover, Communicate and Manage the supported accessories.
5) LocalAuthentication
To use Biometrics Authentication (Touch ID - iPhone5S+). It will only tell you if user authenticated successfully or not to take appropriate action.
6) Metal
It provides support for GPU-accelerated (Apple A7+) advanced 3D graphics rendering, precompiled shaders, state objects, explicit command scheduling and data-parallel computation workloads. It works efficiently Metal shading language.
7) NotificationsUI
Used to create an iOS notification centre widget of an app
8) NetworkExtension
Manage virtual private network with IKEv2/IPSec
9) Photos
Access/Observe/Manage the shared photo library available in both Swift and Objective C
  • Direct photo access in native app and iCloud with PHAssetCollection
  • Full manual control on native camera and Bracketed Capture with the help of AVCaptureDevice
10) PhotosUI
Used to create custom view-controller class as an extension which provide a user interface for editing photo or video assets in iOS Photos app.
11) SceneKit
Processing and animating 3D vector-based graphics, It can work together with SpriteKit as well
12) WebKit
It provides an extended web content rendering support with Java, JavaScript and Media Playback configuration.
13) AVKit
Yet another optimised audio video player view-controller
14) CoreAudioKit
Manage inter app audio player controls
15) NotificationCenter
Both a widget and its containing app can use this API to communicate and specify whether there is content in the widget should display or it should be visible in the Today view or its most recent snapshot is still valid, etc.
16) PushKit

Apple made its admirers quite busy for next few months, cheers folks :)

Using custom UIFont on the fly

Here is yet another code snippet to add a custom font in UIFonts list without previously adding it in your app.plist file, useful while working with library projects and downloading font on the fly.
    NSArray *arrFont = @[@"Comic Sans MS.ttf",@"Tahoma.ttf"];
    for (NSString *str in arrFont) {
        NSString *fontPath = [[NSBundle mainBundle] pathForResource:BUNDLE_NAME ofType:@"bundle"];
        NSData *inData = [NSData dataWithContentsOfFile:[fontPath stringByAppendingFormat:@"/%@",str]];
        CFErrorRef error;
        CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)inData);
        CGFontRef font = CGFontCreateWithDataProvider(provider);
        if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
            CFStringRef errorDescription = CFErrorCopyDescription(error);
            NSLog(@"Failed to load font: %@", errorDescription);

Potential security risks in iOS Apps - Part 1

Few days back Apple developer portal hacked by someone, Do we have a leak in our apps? 

In our busy schedule and tight project deadlines we just want to ignore some basic risks in our app, some people think that Apple environment is close enough to take care of it. Do we are really missing something? yes we are..

These risk increases when we use WebServices, keep files in application folders and don't forget to remove logs while deploying in public domain. Root cause of security holes are:

WebServicesPublicly-Accessible filesInsecure database

I am trying to list down basic things that we can keep in mind while coding:
  1. Use NSTemporaryDirectory or confstr 
  2. Use of higher level APIs like NSFileManager aren't safe enough 
  3. Run static analysis tool frequently. It will not give you all possible issues but it can help with some basics.
  4. Use preprocessor directives to identify the debug environment 
  5. Avoid using NSLog, use some user define macro for logging
    #ifdef DEBUGING
              #define Log( s, ... ) NSLog( @" %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
              #define Log( s, ... )
  6. Always log with formatted string, passing ID to log can create a potential leak
  7. Avoid Cross-site scripting
  8. While opening any URL from a web content check if it is a resource path or a link
  9. Avoid PhoneGap based environment while security is a concern 
  10. Don't trust document serialization and avoid directly executing from the same 
  11. Be aware of trojan/code injection every time you process a downloaded file or file from local directories 
  12. Use hardening techniques
  13. Be aware of security properties of APIs you use 

Useful testing stuffs 
  1. Unit-Testing is your friend 
  2. Crash Wrangler - Fuzzing
  3. Penetration testing

Connecting with iOS

I was just wondering that how to connect with an iPhone, iPod and iPad. The outcome of my research is there are three ways:
An interesting fact is that the antenna for WiFi and Bluetooth is same. To communicate with external accessories there is a ExternalAccessoryFramework.

The architecture of EAF is quite simple, it have a EAProtocol and each span of communication is known as EASession. NSStream helps to carry payload and for input there is NSInputStream and for output there is NSOutputStream

Other core level frameworks like CoreAudio, CoreLocation etc, are also helpful while communicating with an external accessory because they get notification of route change. While we connect or disconnect iOS via dock, EAAccessory notify the app by NSNotificationCenter

  •  EAAccessoryDidConnectNotification
  •  EAAccessoryDidDisconnectNotification

Things to keep in mind
  1. There are no EA events in background we should keep track of application did enter background
  2. Close your EA session as soon as your work is completed 
  3. Antenna arbitration is there
  4. Use accessory change notification generously and be prepared for connectivity loss

Web-Services recapitulate

Now days most of the apps are using WebServices and the good thing is we all know what it is :)

Just adding some notes from my side on things like SOAP, REST and ......., and what? is there anything else do we have in the name of WebService.. really?

Few days ago, a guy who have experience of more then a decade came to me and told me to integrate WebService in an app. I simply asked for WebService summary which I think an usual question while we start working on something. He said to take the reference from an existing website which he pretended that using the same. First I did't get what he wanted to tell but, his steps just gave me heart attack. He just went to Chrome, opened the Website, right clicked for the Inspect element option and while logging in to that website he monitored the Network and said look here is the WebServices just replicate it in your app. After his statement I thought is it worth to ask something anymore?

Okey, letz do a quick recap on what we know:

  1. Charles, Yet simplest tool to monitor a WebService request from an iOS and Mac environment
  2. Each and every resource request to an URI is not a WebService.
  3. One is SOAP and the rest is REST, why do extensive debate
  4. SOAP is XML based definitive object access WebService protocol made for rich guys :)
  5. OAUTH is a two tear authorization framework, ie 

iOS + WS 
  1. Avoid using 3rd party wrappers like ASIHTTP for networking without exploring them
  2. NSURLRequest + NSURLConnection are not an evil
  3. Use event driven APIs
  4. Reachability is our friend
  5. Don't put sync requests on main thread
  6. Your app UI should reflect network reality 
  7. Be prepared for speed latency and packet loss
  8. Be prepared for no network and host not reachable conditions
  9. Always code for insecure connection, use end to end security 
  10. Minimize use of network connections, keep in mind that we also have push notifications 

  1. Always think above $_POST, $_GET, $_REQUEST, $_FILE they are just to help you 
  2. Use and read headers generously
  3. php://input thats what you need 
  4. Don't forget your buddy "MIME types"
  5. Be prepared for Trojan and Injunction
  6. PHP is more related to network, explore its low level possibilities
  7. Take authorization and content distribution seriously

  1. Don't misuse client network and resources :|
  2. Just enjoy with JSON, sometime XML and leave it all for server side :)

Hide blog post from listing based on tags

CSS Part
<b:if cond='data:blog.pageName != &quot;Doodling&quot;'>

iOS - Memory Management

Must follow:
  1. For every alloc, retain, copy you should have a release as soon as you are going to leave it
  2. Avoid using autoreleased objects, You can use autorelease objects but keep in mind that they will not be released until their pool is released
  3. Always respond to memory warnings and take them seriously 
  4. Stick to Lazy Loading, means defer initialization of an object until the point at which it is necessity.
  5. Don't release the objects that we don't own.
  6. Reuse your objects instead of declaring new ones, in possible scenarios.
  7. If you are not using same resource repeatedly then avoid methods like [UIImage imageNamed:@""] because these method will increase cache size, a better alternate is [UIImage imageWithContentsOfFile:@""]
  8. Build custom UITableCell, UICollectionViewCell etc; and reuse them properly
  9. Override setters properly
  10. Use initWithCapacity when size is known to you
  11. Use delegates carefully, remember to set delegate properties to nil before releasing its owner; otherwise, the object might think that its delegate is still there, and will send a message to an invalid pointer.
  12. Use LLVM/Clang Static Analyser tool. It will catch errors regarding the Objective-C naming conventions and hidden memory leaks when using foundation frameworks
Good to have:
  1. Enable Guard Malloc
  2. Enable NSAutoreleaseFreedObjectCheckEnabled
  3. Enable NSZombieEnabled
  4. Enable NSDebugEnabled

गुनाहगारों में आ पहुँचा खतावारों में आ पहुँचा

दयारे ज़ुहुत छोड़ा और मह्ख्वारो में आ पहुंचा
गुनाह ऎ जीस्त की खातिर गुनाहगारों में आ पहुंचा
मेरे दीरा ना हमदम खूब थे पर ये हकीकत है
सबाबित से गुज़र कर आज सैयारों में आ पहुंचा
गुलिस्तानो में रहता था खिज़ा के ज़ोर सहता था
बयाबानो में आ पहुंचा ज़ुनुज़रों में आ पहुंचा
सबिस्तानो के ख़वाब आवर नाज़िर कल की बातें थी
शहर के ज़फिज़ा में बेदार नज़ारों में आ पहुँचा
जो तालिब हैं सुकून ऐ जिंदगी उनको मुबारिक हो
हलाके जूस्तजू था मै की आवारों में आ पहुंचा
नज़र को खीरा कर सकती थी सीमोज़र की ताबानी
नज़र पलती है जिनमे ऐसे नज़रों में आ पहुँचा
मै बेगाना था यज्दा के परिस्तारों की महफ़िल में
ग़नीमत है की इन्सां के परिस्तारों में आ पहुँचा
ऊरूसे ज़िन्दगी की नाज़ परदारी का सौदा था
उरूसे ज़िन्दगी के नाज़ा पर्दारों में आ पहुँचा
अगर यह जिंदगी से प्यार भी एक ज़ुर्म है फ़िर तो
गुनाहगारों में आ पहुँचा खतावारों में आ पहुँचा
भटकता फ़िर रहा था दरबदर और कूबकू  ताबां
यह यारों का तसरुफ़ है की यारों में आ पहुँचा
दयारे ज़ुहुत छोड़ा और मह्ख्वारो में आ पहुंचा
गुनाह ऎ जीस्त की खातिर गुनाहगारों में आ पहुंचा

Error in Personal frameworks after installing new xcode

I have installed the new xcode version with my last xcode version which made me crazy because my project with some personal frameworks are stopped working :(

When I have checked the Framework code it is giving some strange error; "target specifies product type '', but there's no such product type for the 'iphoneos' platform"

After a long long gooooogling in the dark side which did't help me so much. I have found a simple solution, ie;

1) Quit both of XCode versions
2) Switch the active XCode version to the last one (in my case it is; sudo xcode-select --switch /Applications/
3) Reinstall "iOS Real Static Framework"
4) Clean and Build

Do get in touch with me in case you wish to discuss this further. Happy Coding ;)

Blackberry 10 (qnx) PhoneGap Plugins

We have two ways to create plugins for our BlackBerry PhoneGap apps ie; PG-BB Native Java and BB WebWorks

iOS App development with Windows and C

For folks who have Windows and wants to develop an iOS application or if you have written lots of code in C/C++ and just needed a standard API to display images, get touch events, mix sounds, perform file i/o and get access to the iPhone accelerometer data. You just need DragonFireSDK - very cool and inexpensive way to program and test an iPhone app.


Docs URL:

Simple JS minification tool


// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js

// ==/ClosureCompiler==

function hello(name) {
alert('Hello, ' + name);
hello('New user');

add following code with the full path to the files

// @code_url
// @code_url

Convert UIImage to Base64 and vice versa

Code used to convert an image to base64 or an UIImage to base64 NSString

Thats why i do lotz of spelling mistakes without hesitation

I cdnuolt blveiee taht I cluod aulaclty uesdnatnrd waht I was rdanieg. The phaonmneal pweor of the hmuan mnid, aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn’t mttaer in waht oredr the ltteers in a srod are, the olny iprmoatnt tihng is taht the frist and lsat ltteer be in the rghit pclae. The rset can be a taotl mses and you can still raed it wouthit a porbelm.

Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe. Amzanig huh? Yaeh and I awlyas tghuhot slpeling was ipmorantt!

My PhoneGap app not working on ICS

I am working on an phonegap android app since last few months, after the launch of ICS i am shocked that phonegap functions are not supported on it. After some logs and alerts i have found that the code i am using to switch phonegap.js for iOS and Android is incorrect we need to replace it with simple call.

Hacking android app (Basic)

Search and download the apk file, you can use following links to search your apk if you don't have one

convert extension of the file from .apk to .zip and extract this zip, now you get the resources and other files, to get the classes decompile the file classes.dex to jar with an app from this link

Step 1 extract the contents of dex2jar.*.*.zip file
Step 2 copy your .dex file to the extracted directory
Step 3 execute dex2jar.bat <.dex filename> on windows, or ./ <.dex filename> on linux

then you can use jd-gui, the source code is quite readable as dex2jar makes some optimizations.

Frequently used Android Intents

Useful and commonly used Android Intents for frequently used tasks like managing apps, making call, sending SMS, eMail etc

Inspirational Message By Dr.Kalam

Why is the media here so negative?
Why are we in India so embarrassed to recognize our own strengths, our achievements? We are such a great nation. We have so many amazing
success stories but we refuse to acknowledge them.

क्यों मुझे गाँधी पसंद नहीं है?

अमृतसर के जलियाँवाला बाग़ गोली काण्ड (1919) से समस्त देशवासी आक्रोश में थे तथा चाहते थे कि इस नरसंहार के खलनायक जनरल डायर पर अभियोग चलाया जाए। गान्धी ने भारतवासियों के इस आग्रह को समर्थन देने से मना कर दिया।

गब्बर सिंह का चरित्र चित्रण

1.सादा जीवन, उच्च विचार: उसके जीने का ढंग बड़ा सरल था.

JS keyboard shortcuts library

Keymaster (keymaster.js) is a simple micro-library for defining and dispatching keyboard shortcuts with no dependencies on any other framework. Usage is so simple just include keymaster.min.js in your web app, by loading it as usual and write your shortcuts with modifiers like ⇧, shift, option, ⌥, alt, ctrl, control, command, and ⌘., for example;

National anthem truth

I have always wondered who is the " adhinayak"and"bharat bhagya vidhata",whose praise we are singing.. I thought might be Motherland India ! Our current National Anthem "Jana Gana Mana"is sung throughout the country.

Create/Deploy Android project by comand line

Creating and deploying a new Android project by Mac terminal is an exciting experience for me, for this all what i needed are Ant, Mac Terminal and Android SDK only :)

Installing or Upgrading Ant in Mac OSX

First of all Ant already come with Mac OSX, but if you really need to install it or want to upgrade it, though, the best way would be to install it through MacPorts (using sudo port install apache-ant). To install it manually you can follow these simple steps:

Installing and Configuring MacPorts

MacPorts are better way to install and updating various utilities in your mac, it is a command line tool.

Sencha Touch

Sencha Touch is a full mobile JS library, along with widgets, animations and all sort of utilities for mobile html5 development.