Monday, 24 April 2017

Oops Concepts and its use in Objective C

Object Oriented Programming Concepts:


1) Object

It's real time entity. Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

2) Class

Collection of objects is called class. It is a logical entity.


3) Abstraction
Do we thing car as a component which made of different part??
No, we think it as a well designed object which has its unique individual behaviour.

We don't know the internal mechanism of car how it works. From the outside, the car is a single object. Once inside, you see that the car consists of several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so on. In turn, each of these subsystems is made up of more specialized units. For instance, the sound system consists of a radio, a CD player, and/or a tape or MP3 player. The point is that you manage the complexity of the car through the use of hierarchical abstractions.

Hiding internal details and showing functionality is known as abstraction.

- Abstract class can't be instantiated.
- If you implement one or more methods as abstract you have to define that class as abstract class
- You cannot create abstract constructor and abstract static methods.
Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be declared abstract itself.
- You cannot create object but you can use to create object reference 

Example 1:



// A Simple demonstration of abstract.
abstract class A {
 abstract void callme();
 // concrete methods are still allowed in abstract classes
 void callmetoo() {
 System.out.println("This is a concrete method.");
 }
}
class B extends A {
 void callme() {
 System.out.println("B's implementation of callme.");
 }
}
class AbstractDemo {
 public static void main(String args[]) {
 B b = new B();
 b.callme();
 b.callmetoo();
 }
}
// Using abstract methods and classes.
abstract class Figure {
 double dim1;
 double dim2;
 Figure(double a, double b) {
 dim1 = a;
 dim2 = b;
 }
 // area is now an abstract method
 abstract double area();
}
class Rectangle extends Figure {
 Rectangle(double a, double b) {
 super(a, b);
 }
 // override area for rectangle
 double area() {
 System.out.println("Inside Area for Rectangle.");
 return dim1 * dim2;
 }
}
class Triangle extends Figure {
 Triangle(double a, double b) {
 super(a, b);
 }
 // override area for right triangle
 double area() {
 System.out.println("Inside Area for Triangle.");
 return dim1 * dim2 / 2;
 }
}
class AbstractAreas {
 public static void main(String args[]) {
 // Figure f = new Figure(10, 10); // illegal now
 Rectangle r = new Rectangle(9, 5);
 Triangle t = new Triangle(10, 8);
 Figure figref; // this is OK, no object is created
 figref = r;
 System.out.println("Area is " + figref.area());
 figref = t;
08-ch08.indd 183 14/02/14 4:49 PM
CompRef_2010 / Java The Complete Reference, Ninth Edition /Schildt / 007180 855-8
184 PART I The Java Language
 System.out.println("Area is " + figref.area());
 }
}
In second example we create reference.

4) Inheritance:

It is the property by which one object acquires the property of another object.
It used for runtime polymorphism.

There are types of Inheritance.

Single level inheritance

Class A{
}

Class B: public A{
}

Multi level inheritance

Class A{
}

Class B: public A{

}

Class C: public B{


}

Objective-C allows only multilevel inheritance, i.e., it can have only one base class but allows multilevel inheritance. All classes in Objective-C is derived from the superclass NSObject.

Multiple inheritance

Class A{
}

Class B{

}

Class C: public A, public b{


}

Objective C doesn't support Multiple inheritance

Hierarchical inheritance

Class A{
}

Class B: public A{

}

Class C: public A{


}

Hybrid inheritance

Class A{
}

Class B{

}

Class C: public A, public B{



}

Class D: public A{


}

5) Encapsulation:

wrapping of data and code together  in a single unit is called  Encapsulation.

The very good example of encapsulation is class.

    class Box
    {
       public:
          double getVolume(void)
          {
             return length * breadth * height;
          }
       private:
          double length;      // Length of a box
          double breadth;     // Breadth of a box
          double height;      // Height of a box
    };

6) Polymorphism:

There are two types of polymorphism.

Runtime(Dynamic) - Method overriding


Method overriding is a perfect example of  runtime polymorphism. In this kind of polymorphism, reference of class X  can hold object of class X or an object of any sub classes of class X. For e.g. if class Yextends class X then both of the following statements are valid:

Y obj = new Y();
//Parent class reference can be assigned to child object
X obj = new Y();

Compile time - Method overloading
Compile time polymorphism is nothing but the method overloading in java. In simple terms we can say that a class can have more than one methods with same name but with different number of arguments or different types of arguments or both. To  know more about it refer method overloading in java.

Monday, 19 September 2016

SiriKit in iOS


   There are so many variation we found in ios 10 for app extension. I here describe one of them and it is Intent and IntentUI app extension
          
         Till now you cannot use SiriKit in ios application :(. But.......... 
         Now in ios 10 you can use sirikit in your ios application  :)
       


       
Siri is introduces from ios5. Now we can use it in our application.
 SiriKit is a new iOS developer framework that allows third-party apps from the App Store to              integrate their features with Siri.
 SiriKit is an app extension that allows any app to add a conversational UI.
 If your app  want to support sirikit then it has to support following domains:
  1. VoIP calling
  2. Messaging
  3. Payments
  4. Photo
  5. Workouts
  6. Ride booking
  7. CarPlay (automotive vendors only)
  8. Restaurant reservations (requires additional support from Apple)

Each domain represent one or more tasks. Each task can be represent an intent.each intent is represented by a custom class whose properties contain information related to the task. For example, intents in the Payments domain contain properties with the amount of money to transfer and the users involved in the transaction. When the user makes a request through Siri or Maps, the system fills an intent object with the details of the request and delivers that object to your app extension. You use the intent object to validate the request data and perform the associated task.

Intent and IntentUI 

Intent : Intent extension that receives information from the system and return the response.

IntentUI : Used to show custom user interface  to the user.

To understand Sirikit you have to understand app extension.

App extension works in this way :

If you open photos app and tap on share button you can see the instagram icon .Here Photos is a host application. when tap on share icon instagram extension open.
Here apple provided flow how all this work.





Now we focus back on sirikit:

How siri actual work we take an example of chat application.

If i say hey "send message to Prerak" then what happen.... Prerak name is not in database of siri. but its is in database of whatsapp. Now whatsapp developer share the contact details of Prerak to siri. You can share album name, workout name then siri check if there are some mission information. Siri recongnize that on message domain you have message to send. To solve this siri will ask what message you want to send to Prerak. After all this steps siri wraps all you data in intent. It then passes that intent object to your application for you to perform the logic on, and waits for a response to confirm the action with the user. If you are implementing Siri in your app, the name that users will use to summon your application, is the same as the name that is listed below your app on the home screen.

The programming part we will cover in the next blog...:)

Friday, 15 April 2016

Linkdin Login in ios application

In one of my application i have to provide option that user can login though linkdn.

First of all make 

1) Add linkedin-sdk framework in your project

2) Get access token from this method:

[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil]
                                     state:@"some state"
                                     showGoToAppStoreDialog:YES
                                               successBlock:^(NSString *returnState) {

                                                   NSLog(@"%s","success called!");
                                                   LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
                                                   NSLog(@"value=%@ isvalid=%@",[session value],[session isValid] ? @"YES" : @"NO");
                                                   NSMutableString *text = [[NSMutableString alloc] initWithString:[session.accessToken description]];
                                                   [text appendString:[NSString stringWithFormat:@",state=\"%@\"",returnState]];
                                                   NSLog(@"Response label text %@",text);
                                                   _responseLabel.text = text;
                                                   self.lastError = nil;
                                                   // retain cycle here?
                                                   [self updateControlsWithResponseLabel:NO];

                                               }
                                                 errorBlock:^(NSError *error) {
                                                     NSLog(@"%s %@","error called! ", [error description]);
                                                     self.lastError = error;
                                                     //  _responseLabel.text = [error description];
                                                     [self updateControlsWithResponseLabel:YES];
                                                 }
     ];
   
3) if you want id,first-name,last-name,maiden-name,email-address after authorization you can apply this code:

   [[LISDKAPIHelper sharedInstance] apiRequest:https://www.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)
                                             method:method
                                               body:nil
                                            success:^(LISDKAPIResponse *response) {
                                                NSLog(@"success called %@", response.data);
                                                AppDelegate *myAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                                dispatch_sync(dispatch_get_main_queue(), ^{
                                                    [myAppDelegate showAPIResponsePage:method
                                                                                status:response.statusCode
                                                                               request:_resourceTextField.text
                                                                              response:response.data];
                                                });
                                            }
                                              error:^(LISDKAPIError *apiError) {
                                                  NSLog(@"error called %@", apiError.description);
                                                   AppDelegate *myAppDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
                                                  dispatch_sync(dispatch_get_main_queue(), ^{
                                                      LISDKAPIResponse *response = [apiError errorResponse];
                                                      NSString *errorText;
                                                      if (response) {
                                                          errorText = response.data;
                                                      }
                                                      else {
                                                          errorText = apiError.description;
                                                      }
                                                  [myAppDelegate showAPIResponsePage:[self getMethod]
                                                                              status:[apiError errorResponse].statusCode
                                                                             request:_resourceTextField.text
                                                                            response:errorText];
                                                  });
                                              }];

 
you can check your method output by this link:

https://apigee.com/console/linkedin
 

Get the crash log from console

I am developing one of application which crashes in 64 devices  which i don't have. My client is outside from company and i have to upload the build and check the log . He has to mail me crash log.

For that i apply this functionality which  anyone can use.

This function can be used to write the log in document folder and then email them.

    - (IBAction)redirectLogToDocuments
        {
            if ([MFMailComposeViewController canSendMail]==TRUE) {


            NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [allPaths objectAtIndex:0];
            NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"clipboard.txt"];

            freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);

            NSString *emailTitle = @"Email Log";
            // Email Content
            NSString *messageBody = @"Check Log to view from where application stop";
            // To address
            NSArray *toRecipents = [NSArray arrayWithObject:@"support@appcoda.com"];

            MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
            mc.mailComposeDelegate = self;
            [mc setSubject:emailTitle];
            [mc setMessageBody:messageBody isHTML:NO];
            mc.modalPresentationStyle = UIModalPresentationCurrentContext;
            [mc setToRecipients:toRecipents];
            NSData *fileData = [NSData dataWithContentsOfFile:pathForLog];
            [mc addAttachmentData:fileData mimeType:@"text/plain"  fileName:@"clipboard.txt"];

            // Present mail view controller on screen
            //[self presentViewController:mc animated:YES completion:nil];
            [self presentViewController:mc animated:YES completion:^{

            }];
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Please configure mail" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [alert show];
            }

        }


  - (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
    {
        NSString *strMessage;
        switch (result)
        {
            case MFMailComposeResultCancelled:
                NSLog(@"Mail cancelled");
                strMessage = @"Mail cancelled";
                break;
            case MFMailComposeResultSaved:
                NSLog(@"Mail saved");
                strMessage = @"Mail save";
                break;
            case MFMailComposeResultSent:
                strMessage = @"Mail sent";
                NSLog(@"Mail sent");
                break;
            case MFMailComposeResultFailed:
                NSLog(@"Mail sent failure: %@", [error localizedDescription]);
                 strMessage = @"Mail sent failure";
                break;
            default:
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:strMessage delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        [self dismissViewControllerAnimated:YES completion:NULL];
    }

Thats it you are done now you can mail yout whole log of application by mail.

Happy Coding!!!!

Thursday, 22 October 2015

Proximity in IOS application


First of all what is proximity in IOS ?

Do you ever play audio in Whatsapp in iphone ? when it is playing far from the face its volume is high and when you take it near to your ear or face then you can hear the audio in Receiver from microphone. This functionality is implemented by checking proximity.

First  Proximity can not be checked in Ipod and Ipad , You can check whether your device support Proximity or not by implement this code.

      
UIDevice *device = [UIDevice currentDevice];
device.proximityMonitoringEnabled = YES;    

if (device.proximityMonitoringEnabled == YES) // yes your device support proximity
{
    NSLog(@"proximity enabled");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityChanged:) name:@"UIDeviceProximityStateDidChangeNotification" object:device];
} else {
    NSLog(@"proximity not enabled");
}


When proximity change you can change your avaudiosession property When your device is near to your face you can overrideOutputAudioPort to    AVAudioSessionPortOverrideNone and when your
device is far from your face you can overrideOutputAudioPort to    AVAudioSessionPortOverrideSpeaker so it will play in speaker

- (void) proximityChanged:(NSNotification *)notification {
    NSLog(@"proximity changed called");
    UIDevice *device = [notification object];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL success;
     success = [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    if(device.proximityState == 1){
        NSLog(@"bool %s", success ? "true" : "false");
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
        [audioSession setActive:YES error:nil];
    }
    else{
        NSLog(@"bool %s", success ? "true" : "false");
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
        [audioSession setActive:YES error:nil];
        }
}


Now proximity should be off when it is not needed , that's why in viewWillAppear of each screen you should make it of and only when your audio is playing on it .

 -(void)viewWillAppear:(BOOL)animated
    {   
        [super viewWillAppear:animated];

        UIDevice *device = [UIDevice currentDevice];

        device.proximityMonitoringEnabled = NO;
    }

Monday, 5 October 2015

StoryBoard Reference in Xcode 7


If you have multiple Storyboard in your project if you want to navigate from one storyboard to other storyboard until Xcode 6.4 you have to use this code  :

first make object of storyboard , then make object of that storyboard's view controller

      self.myProfileStoryboard = [UIStoryboard storyboardWithName:@"MyProfile"
                                                        bundle: nil];
     
      self.homeNavC = (AHKNavigationController*)[self.homeStoryboard
 
                                             instantiateViewControllerWithIdentifier: @"HomeViewControllerIDNavCntrl"];



But now in Xcode 7 you can use  Storyboard Reference


1) Make one storyboard , add one navigationController and add one ViewController name it FirstViewController

















2) In First Storyboard add one storyboard Reference as under

3) Add  one ViewController in  second storyboard 
4) In second storyboard gave StoryboardId - SecondViewID for that viewController 






5)  Select FirstView Controller and gave the values as under:



Thats you done run your project and you can see you can navigate from one storyboard to another storyboard using StoryBoard Reference.


But this project you can not open now in previous xcode if you open you will see following error 








Friday, 14 August 2015

Emoji support in ios Application

Open the emoji keyboard


You can find the emoji keyboard in any app that uses the standard keyboard. Tap in a text field, then tap Smiley face icon. If you have multiple keyboards turned on, press and hold Globe icon, then select Emoji




In iOS 8.3 and later, you can change the skin tone of some emoji. Tap and hold an emoji to see different skin tone variations. When you choose a skin tone, it will be saved as the default.


If you don't see the emoji keyboard
Make sure that the emoji keyboard is turned on:
  1. Tap Settings > General > Keyboard.
  2. Tap Keyboards.
  3. Tap Add New Keyboard.
  4. Tap Emoji.

Now how to support in IOS application 

In one of my application i have to send description in which i am adding smily :) . i have to encode the text and then send them and as well when i am displaying them i have to convert them . Lets see how.

When you send to server:


    NSString *uniText = [NSString stringWithUTF8String:[self.txtDesc.text UTF8String]];
    NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
    NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding] ;


and we display text do this way:


    -(NSString*)displayEmojiText:(NSString*)strText{
        NSData *emojiData = [strText dataUsingEncoding:NSUTF8StringEncoding];
        NSString *emojiString = [[NSString alloc] initWithData:emojiData encoding:NSNonLossyASCIIStringEncoding];
        return emojiString;
    }

[self.lblPostDescription setText:[APP_DELEGATE displayEmojiText:description]]