Tuesday, May 31, 2016

Migrating Objective C code to Swift


Migration provides an opportunity to revisit an existing Objective-C app and improve its architecture, logic, and performance by replacing pieces of it in Swift. For a straightforward, incremental migration of an app, you’ll be using the tools learned earlier—mix and match plus interoperability. Mix-and-match functionality makes it easy to choose which features and functionality to implement in Swift, and which to leave in Objective-C. Interoperability makes it possible to integrate those features back into Objective-C code with no hassle.

The most effective approach for migrating code to Swift is on a per-file basis—that is, one class at a time. Because you can’t subclass Swift classes in Objective-C, it’s best to choose a class in your app that doesn’t have any subclasses. You’ll replace the .m and .h files for that class with a single .swift file. Everything from your implementation and interface goes directly into this single Swift file. You won’t create a header file; Xcode generates a header automatically in case you need to reference it


Below are the steps

1) Create a Swift class for your corresponding Objective-C .m and .h files by choosing File > New > File > (iOS, watchOS, tvOS, or OS X) > Source > Swift File. You can use the same or a different name than your Objective-C class. Class prefixes are optional in Swift.
2) Import relevant system frameworks.
3) Fill out an Objective-C bridging header if you need to access Objective-C code from the same app target in your Swift file.
4) To make your Swift class accessible and usable back in Objective-C, make it a descendant of an Objective-C class. To specify a particular name for the class to use in Objective-C, mark it with @objc(name), where name is the name that your Objective-C code uses to reference the Swift class.

references:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/Migration.html

Swift Mid And Match



Swift’s compatibility with Objective-C lets you create a project that contains files written in either language. You can use this feature, called mix and match, to write apps that have a mixed-language codebase.

To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.

If you accept, Xcode creates the header file along with the file you were creating, and names it by your product module name followed by adding "-Bridging-Header.h". (You’ll learn more about the product module name later, in Naming Your Product Module.)

Alternatively, you can create a bridging header yourself by choosing File > New > File > (iOS, watchOS, tvOS, or OS X) > Source > Header File.

In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift. For example:
#import "XYZCustomCell.h"
#import "XYZCustomView.h"
#import "XYZCustomViewController.h"

references:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Apple Watch - How to it behaves on receiving phone calls





If someone calls you while you're wearing your Apple Watch (and it's paired to your iPhone), you'll be alerted by a subtle vibration as well as an audible ringtone if you haven't set the device to silent.

Look at your watch and you'll see who's calling, along with an answer or decline button. If it's someone you want to talk to, tap the green answer button. There's a built-in speaker and microphone, so you'll be able to chat without getting your iPhone out of your bag or pocket.

Should you wish to take the phone call on your iPhone (don't forget that everyone else will be able to hear your conversation if you're speaking through your wrist unless you're using a Bluetooth headset), you can seamlessly transfer the call from the Apple Watch to your iPhone by scrolling up using the Digital Crown and tapping 'Answer on iPhone.'

references:
http://www.macworld.co.uk/how-to/apple/guide-phone-calls-on-apple-watch-3607555/

Apple Watch handling Notification actions

First of all, we need to create categories

    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    acceptAction.activationMode = UIUserNotificationActivationModeBackground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    
    UIMutableUserNotificationAction *rejectAction = [[UIMutableUserNotificationAction alloc] init];
    rejectAction.identifier = @"REJECT_IDENTIFIER";
    rejectAction.title = @"Reject";
    rejectAction.activationMode = UIUserNotificationActivationModeBackground;
    rejectAction.destructive = NO;
    rejectAction.authenticationRequired = NO;
    
    UIMutableUserNotificationCategory *notificationCategory = [[UIMutableUserNotificationCategory alloc] init];
    notificationCategory.identifier = @"CALL_NOTIFICATION_CATEGORY";
    [notificationCategory setActions:@[acceptAction,rejectAction]forContext:UIUserNotificationActionContextDefault];
    
    NSSet *categories = [NSSet setWithObjects:notificationCategory, nil];
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:categories];
    

    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

Now on the App Delegate of the companion app, can override the method


- (void)application:(UIApplication *) application handleActionWithIdentifier: (NSString *) identifier forLocalNotification: (NSDictionary *) notification completionHandler: (void (^)()) completionHandler {

if ([identifier isEqualToString: @"ACCEPT_IDENTIFIER"])
        {
            NSLog(@"Accept is pressed");
            OngoingCallScreen *callScreen = [OngoingCallScreen sharedScreen];
            NSArray *callSessions = [callScreen getActiveCalls];
            NSLog(@"Call Sessions Are :%@",callSessions);
            if([callSessions count] > 0)
            {
                [callScreen handleCallEvent:CallEventToAnswerIncomingCall with:[callSessions objectAtIndex:0]];
            }
            
        }
        else
        {
            NSLog(@"Reject is pressed");
            OngoingCallScreen *callScreen = [OngoingCallScreen sharedScreen];
            NSArray *callSessions = [callScreen getActiveCalls];
            NSLog(@"Call Sessions Are :%@",callSessions);
            if([callSessions count] > 0)
            {
                [callScreen handleCallEvent:CallEventToRejectIncomingCall with:[callSessions objectAtIndex:0]];
            }
        }
   completionHandler();
}

references:
https://developer.apple.com/library/ios/documentation/General/Conceptual/WatchKitProgrammingGuide/BasicSupport.html#//apple_ref/doc/uid/TP40014969-CH18-SW1

CGPDFDocumentRef

The CGPDFDocumentRef opaque type encapsulates a document that contains PDF (Portable Document Format) drawing information. PDF provides an efficient format for cross-platform exchange of documents with rich content. PDF files can contain multiple pages of images and text. A PDF document object contains all the information relating to a PDF document, including its catalog and contents.

Note that PDF documents may be encrypted, and that some operations may be restricted until a valid password is supplied—see the functions listed in Managing Encryption. Quartz also supports decrypting encrypted documents.

Quartz can both display and generate files that are compliant with the PDF standard. When imaging PDF files, CGPDFDocumentRef is the basic type used to represent a PDF document.

references:

Creating Actionable Notifications on Apple Watch

In iOS 8 and later, apps are required to register the types of notification-generated alerts they display using a UIUserNotificationSettings object. When registering that information, the app can also register a set of custom notification categories, which include the actions that can be performed for that category. Apple Watch uses this category information to add the corresponding action buttons to the long-look interface.

Support for text input is new in watchOS 2 and iOS 9. When enabled, text input lets the user respond to the notification with a short message. On Apple Watch, the user can either dictate a text response or select from a set of predefined messages. to enable the text input, we need to add the UIUserNotificationActionBehaviorTextInput value to the behaviour property of the UIUserNotificationAction that we create in iOS. 

Below given some details on how to respond to the user actions

When the user taps an action button for a notification, the system uses the information in the registered UIUserNotificationAction object to determine how to process the action. Actions can be processed in the foreground or the background. Foreground and background actions are processed differently:

Foreground actions launch your Watch app and deliver the ID of the tapped button to your extension delegate’s notification methods.
For remote notifications, the WatchKit extension calls the handleActionWithIdentifier:forRemoteNotification: or handleActionWithIdentifier:forRemoteNotification:withResponseInfo: method.
For local notifications, the WatchKit extension calls the handleActionWithIdentifier:forLocalNotification: or handleActionWithIdentifier:forLocalNotification:withResponseInfo: method.

Background actions launch the iOS app in the background so that it can process the action. Information about the selected action is delivered to the app delegate’s notification methods.

For remote notifications, iOS calls the application:handleActionWithIdentifier:forRemoteNotification:completionHandler: or application:handleActionWithIdentifier:forRemoteNotification:withResponseInfo:completionHandler: method.
For local notifications, iOS calls the application:handleActionWithIdentifier:forLocalNotification:completionHandler: or application:handleActionWithIdentifier:forRemoteNotification:withResponseInfo:completionHandler: method.

Selecting the foreground action launches the app to handle the action. Your app’s extension delegate must implement the appropriate methods to process actions.

The specific method called by watchOS depends on whether the action included a text response from the user. Text input triggers the method that includes the responseInfo parameter. Action buttons trigger the method without responseInfo. 

The user’s string is passed inside the responseInfo dictionary. You can access the string using the UIUserNotificationActionResponseTypedTextKey key, and then incorporate that string into any actions that handle the notification. For example, if the user declined a meeting invite, you can add the text response to the invite so that the originator knows why the user declined.

To provide suggested responses for the text input, override the notification interface controller’s suggestionsForResponseToActionWithIdentifier:forRemoteNotification:inputLanguage: or suggestionsForResponseToActionWithIdentifier:forLocalNotification:inputLanguage: method and return an array of strings. watchOS presents these strings as suggestions.

If a notification arrives while the user is interacting with your Watch app, watchOS delivers the notification to the didReceiveRemoteNotification: or didReceiveLocalNotification: method of your extension delegate. You can use these methods to refresh your interface or take other actions based on the data in the notification.


references:

Sunday, May 29, 2016

Watch Connectivity Framework

The WCSession class facilitates communication between a WatchKit extension and its companion iOS app. Both processes must create and configure an instance of this class at some point during their execution. When both session objects are active, the two processes can communicate immediately by sending messages back and forth. When only one session is active, the active session may still send updates and transfer files, but those transfers happen opportunistically in the background.


if ([WCSession isSupported]) {
    WCSession* session = [WCSession defaultSession];
    session.delegate = self;
    [session activateSession];
}

You may initiate data transfers to a counterpart app only when the activationState property is set to WCSessionActivationStateActivated. 

Below are the communication options between watch app and companion app

Use the updateApplicationContext:error: method to communicate recent state information to the counterpart. When the counterpart wakes, it can use this information to update its own state. For example, an iOS app that supports Background App Refresh can use part of its background execution time to update the corresponding Watch app. This method overwrites the previous data dictionary, so use this method when your app needs only the most recent data values.

Use the sendMessage:replyHandler:errorHandler: or sendMessageData:replyHandler:errorHandler: method to transfer data to a reachable counterpart. These methods are intended for immediate communication between your iOS app and WatchKit extension. The reachable property must currently be YES for these methods to succeed.

Use the transferUserInfo: method to transfer a dictionary of data in the background. The dictionaries you send are queued for delivery to the counterpart and transfers continue when the current app is suspended or terminated.

Use the transferFile:metadata: method to transfer files in the background. Use this method in cases where you want to send more than a dictionary of values. For example, use this method to send images or file-based documents.


references:
https://developer.apple.com/library/watchos/documentation/WatchConnectivity/Reference/WCSession_class/

Google Fit APIs - at High level

Google Fit APIs 

Fit is an open platform that lets users control their fitness data, developers build smarter apps, and manufacturers focus on creating amazing devices.

The main target of these APIs are 

Discover Sensors => Easily view available sensor data sources from connected apps and devices with the Sensors API.
Collect Activity Data => Connect your app and devices to Google Fit with the Recording API.
Help users keep track => Access and edit the user's fitness history with the History API.

Below are major components of the Fit ecosystem 

1. The Fitness Store => A central repository that stores data from a variety of devices and apps. The fitness store is a cloud service that is transparent to clients.
2. The Sensor Framework => A set of high-level representations that make it easy to work with the fitness store. You use these representations with the Google Fit APIs.
3. Permissions And User Controls => A set of authorization scopes to request user permission to work with fitness data. Google Fit requires user consent to access fitness data.
4. Google Fit APIs => Android and REST APIs to access the fitness store. You can create apps that support Google Fit on multiple platforms and devices, such as Android, iOS, and Web apps.


references:

Sunday, May 8, 2016

Developing For Apple Watch concepts

The projects you create for Apple Watch consist of two separate bundles: a Watch app and a WatchKit extension. The Watch app bundle contains the storyboards and resource files associated with all of your app’s user interfaces. The WatchKit extension bundle contains the extension delegate and the controllers for managing those interfaces and for responding to user interactions. While these bundles are distributed inside an iOS app, they are then installed on the user’s Apple Watch and run locally on the watch.


A watchOS project must include a watch app, but may also include a glance, custom notifications, and complications. Each of these provide unique way for users to interact with the app. The glance, notifications and complications are not separate executables. instead, the interface for the glance and notifications are included in the Watch apps storyboard. The code for managing the glances, notifications and complications are part of watch kit extension. 

The Watch App: 

The Watch app is the actual app that the user launches from the Apple Watch Home screen. The Watch app presents your app’s full user interface. The app supports one or more screens of custom content that you define. Use the Watch app to present all of the content you support on Apple Watch, which is often only a subset of the content you support in your iOS app.

The Glance Interface:
A glance is meant to be looked at quickly. With a swipe from the bottom of the watch face, a glance displays the app’s most important information. Glances are nonscrolling; the entire glance interface must fit on a single screen, and the information in a glance is read-only, and hence do not contain buttons, switches, or other interactive controls. Tapping a glance launches the Watch app’s main interface.

Custom and Actionable Notifications
Apple Watch works with its paired iPhone to display local and remote notifications. Initially, Apple Watch uses a minimal interface—called a short look—to display incoming notifications. If the user’s wrist remains raised, the minimal interface changes to a more detailed interface—called a long look—displaying the contents of the notification. You can customize the long look, adding custom graphics or arranging the notification data differently from the default interface provided by the system.

Apple Watch also provides automatic support for actionable notifications. Actionable notifications let app to add buttons or text input to the notification interface, so that users can respond directly to the notification. 

When the iOS app registers support for actionable notifications, Apple Watch automatically adds buttons for notification actions to the notification interfaces on Apple Watch. All the app need to do is handle the user’s actions in your WatchKit extension.

Complications:
Complications are small visual elements that appear directly on the watch face and convey important information to the user. Complications are automatically visible whenever the user looks at Apple Watch to check the time. Most watch faces support at least two or three complications, and the user can customize which complications are displayed. Apps may use a complication to display app-specific data.

references:

Amazon AWS running java code on separate screen

When an Java program is run on the same window as the EC2 login, when the window closes, the program also terminates. To avoid this, the program can be run on separate screen. the commands is below

$screen

Now even if the window is closed, the program continue to run.

Now after logging in again, if want to access the screen, can type in the below

$screen -r

references:
http://cs.smith.edu/dftwiki/index.php/Tutorial:_So_you_want_to_run_your_code_on_Amazon%3F

Wednesday, May 4, 2016

Create a Database server on AWS

We can use Amazon Relational Database server (RDS) to run the database. When we launch a Multi-AZ DB instance, Amazon RDS automatically provisions and maintains a synchronous standby replica in different availability zone. Updates to the DB instance are synchronously replicated across availability zones to standby inorder to keep them in sync and protect the database update against DB failure. 

First step is to create security group for DB instance

1) Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
2) In the navigation pane, click Security Groups, and then click Create Security Group.
3) Enter DBServerSG as the name of the security group, and provide a description.
Select your VPC from the list.
4) On the Inbound tab, click Add Rule. Select MYSQL/Aurora from the Type list. Under Source, select Custom IP, start typing WebServerSG in the text box, and then select the WebServerSG security group.
Create a security group for your database server.
Click Create.

Next step is to Launch DB instance
1) Open the Amazon RDS console at https://console.aws.amazon.com/rds/.
2) In the navigation bar, verify that US West (Oregon) is the selected region.
3) In the navigation pane, click Subnet Groups, and then click Create DB Subnet Group.
4) Complete the Create DB Subnet Group page as follows:
5) Enter a name in Name. For example, my-db-subnet-group.
6) Enter a description in Description.

Select your VPC from VPC ID.

In Availability Zone, select the first Availability Zone from the list. Select the private subnet from Subnet ID, and then click Add.
In Availability Zone, select the second Availability Zone from the list. Select the private subnet from Subnet ID, and then click Add.
Click Create.

In the navigation pane, click Instances, and then click Launch DB Instance.
On the Select Engine page, select the MySQL tab, and then click Select.
On the Do you plan to use this database for production purposes page, under Production, select MySQL, and then click Next Step.
On the Specify DB Details page, do the following:
Keep the default license model and the default DB engine version.
Select db.t2.micro from DB Instance Class.
In Multi-AZ Deployment, select Yes. Although the Multi-AZ deployment is more expensive, it is a best practice.
Select General Purpose (SSD) from Storage Type and keep the default value for Allocated Storage.
In DB Instance Identifier, enter my-db-instance.
In Master Username, enter db_user.
Enter a password in Master Password and Confirm Password. Record your password in a safe place.
Click Next Step.

references:

Setting up to Host a Web app on AWS

Once the account is setup, first task is to create an IAM user. If one has signed up for AWS but not yet created the IAM account, then that can be done using the IAM console. 

The basic concept is to create Group and add users to the Group. 

1. Sign in to the IAM console which is at https://console.aws.amazon.com/iam/
2. Now Create Group from the options Groups, Create New Group, From the list of policies, assign a policy such as AdministratorAccess 
3. Now create Users and add the users to Group. Users, Create New Users, also check generate Access key for each user option, Create. 
4. Now choose Groups and add users to group. Choose Security Credentials for each user and under sign in credentials, choose manage password. Select assign custom passoword and apply. 

now logout and login with the created user. To do this, the sign in URL will be of the form https://your_aws_account_id.signin.aws.amazon.com/console/

The next step is to create a Key pair. 
AWS uses the public key cryptography to secure login information to the instance. A linux has no password, instead use key value pair. One need to specify the name of the key pair when launching the instance and then provide the private key when login using SSH. 

Using AWS console, one can create key pair. 

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
From the navigation bar, in the region selector, click US West (Oregon).
In the navigation pane, click Key Pairs.
Click Create Key Pair.
Enter a name for the new key pair in the Key pair name field of the Create Key Pair dialog box, and then click Create. Choose a name that is easy for you to remember.

Below was the name given for the key pair in the console. The file was downloaded with the below name assistedaccesspair.pem 
Now we needed to give change mode of this file, which can be done using the command chmod 400 assistedaccesspair.pem 

Now we need to configure the Virtual Private Cloud. 

Amazon VPC allows the AWS resources to be deployed into the VPC if desired. To test if we have a VPC, below steps to be followed. 

Normally, the setup will have a default VPC, to check if we have default VPC, below steps can be followed. 

Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
In the navigation bar, verify that US West (Oregon) is the selected region.
In the navigation pane, click Your VPCs.
One of the following is true:
The list is empty, so you do not have a default VPC.
The list has a default VPC (a VPC with a CIDR block of 172.31.0.0/16).
The list has one or more non-default VPCs (a VPC with a CIDR block that is not 172.31.0.0/16).


Did not create another VPC as was okay with the default VPC.

references: