Friday, June 20, 2014

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 )