Monday, November 30, 2015

Introduction to CocoaPods Tutorial


CocoaPods Tutorial

Instead of downloading code from GitHub and copying it into your project (and thus making future updates difficult), you can let CocoaPods do it for you.
You will retrieve show information from a JSON feed provided by trakt. To simplify downloading, parsing, and showing results, you will use AFNetworking and a few other open-source libraries along the way.
To get started, you first need to install CocoaPods. CocoaPods runs on Ruby, yet that’s the only dependency it has. Fortunately, all recent versions of Mac OS X (since OS X 10.7 Lion) ship with Ruby already installed. So all you need to do is update RubyGems (just to make sure you have a recent version).
To do so, open Terminal and type the following command:
sudo gem update --system
Enter your password when requested. The Terminal output should look something like this:
Terminal Output
This update may take a little while, so be patient and give it a few minutes to complete. You can also expect some documentation in the Terminal window about the latest version; you can ignore this for now.
Next, you need to install CocoaPods. Type this command in Terminal to do so:
sudo gem install cocoapods
You may get this prompt during the install process:
rake's executable "rake" conflicts with /usr/bin/rake
Overwrite the executable? [yN]
If so, just enter y to continue. (This warning is raised because the rake gem is updated as part of the install process. You can safely ignore it.)
Lastly, enter this command in Terminal to complete the setup of CocoaPods:
pod setup
This process will likely take a while as this command clones the CocoaPods Specs repository into~/.cocoapods/ on your computer.
Great, you’re now setup to use CocoaPods!

Open Project that you created

Open Main.storyboard, and you will see just one view controller:

View Controller
Yeah, you read that right! It’s time to create your pod file.

Installing Your First Dependency

Open Terminal and navigate to the directory containing your ShowTracker project by using the cd command:
cd ~/Path/To/Folder/Containing/PiyushDemo
Next enter this command:
pod init
This will create a default Podfile for your project. The Podfile is where you define the dependencies your project relies on.
Type this command to open Podfile using Xcode for editing:
open -a Xcode Podfile
# Uncomment this line to define a global platform for your project
# platform :ios, "6.0"
 
target "ShowTracker" do
 
end
Replace # platform :ios, "6.0" with the following:
platform :ios, "7.0"
This tells CocoaPods that your project is targeting iOS 7.
Many libraries – AFNetworking included – have a minimum iOS version requirement. If you omit this line, CocoaPods assumes a default target version (currently iOS 4.3).
If you’ve only ever programmed in Objective-C, this may look a bit strange to you – that’s because the pod file is actually written in Ruby. You don’t need to know Ruby to use CocoaPods, but you should be aware that even minor text errors will typically cause CocoaPods to throw an error.
It’s finally time to add your first dependency using CocoaPods! Copy and paste the following into your pod file, right after target "ShowTracker" do:
pod 'AFNetworking', '2.2.1'
This tells CocoaPods that you want to include AFNetworking version 2.2.1 (the latest as of the writing of this tutorial) as a dependency for your project.
Save and close the pod file.
You now need to tell CocoaPods to “install” the dependencies for your project. Enter the following command in Terminal to do so (making sure that you’re still in the directory containing the ShowTracker project and Podfile):
pod install
You should see output similar to the following:
Analyzing dependencies
Downloading dependencies
Installing AFNetworking (2.2.1)
Generating Pods project
Integrating client project
It might also tell you something like this:
[!] From now on use `ShowTracker.xcworkspace`.
If you type ls now (or browse to the project folder using Finder), you’ll see that CocoaPods created a Pods folder – where it stores all dependencies – and ShowTracker.xcworkspace.

UIViewController Lifecycle

ViewController LifeCycle



Today we are going to discuss only about the ViewController LifeCycle and How we should use each of the methods provided in the lifecycle event.

What is LifeCycle?

LifeCycle is an event which have certain steps from the point of creation to deletion. So how do we know about the steps during this period? A Sequence of methods are called as they progress through the LifeCycle. 

Now we may need to perform different kind of actions at different steps of the life cycle and thus we commonly override these methods and perform these actions.

As I said the Start of LifeCycle is Creation. Most of the MVCs are Instantiated through the StoryBoard. So what happen after the creation of the ViewController?

  • Outlet setting
  • View Appear and Disappear
  • Changes in the  Geometry
  • Memory Warnings
At each of the above step iOS invokes methods on the viewControllers. We will discuss each of the methods in detail.

ViewController LifeCycle Methods


awakeFromNib

This is Strictly not part of the viewController lifeCycle but still play a role in the initialization of the viewController. This method is called on all the objects which come out of the StoryBoard. This happens before all the outlet are set i.e. before the loading of the view. Before you put any code in here you must think if you can put it somewhere else may be viewDidLoad or viewWillAppear. 

Note: Init method is not called on the objects which came out of the StoryBoard. So you might want to put the code written in the Init method in the awakeFromNib method too.

viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

This is good place to put your setup code for the View. Always call the super class method to complete the lifeCycle methods. At this point of time of LifeCycle we are not sure of the Geometry of the Device so you do not put any code that is based on the Geometry of the view.

viewWillAppear

- (void)viewWillAppear:(BOOL)animated

Notification to the viewController when view is just about to View on the screen. animated argument tells whether you are appearing Instantly or after sometime via an animation. This method can be overridden to change the color or something else of the status bar according to the orientation or as per the style of the view.

Note: As you understand that view will be loaded once, however it will appear and disappear again and again. So you do not want to write a piece of code in this method which actually belongs in viewDidLoad, otherwise you will be doing the same thing again and again.

viewWillDisappear

- (void)viewWillDisappear:(BOOL)animated

Notify the controller that view is about to be removed from the screen. This is the place you will write code like storing the state of the view or Cleaning up the resources being used. animated argument is again to tell whether are are disappearing instantly or via an animation.

We might not want to write code thats time consuming. We can kick off some thread which can do the task in the background.

There are did versions of both the viewWillAppear and viewWillDisapper methods viewDidAppear and viewDidDisappear which are called after the view is appeared and view is disappeared relatively.

viewWillLayoutSubviews

- (void)viewWillLayoutSubviews

This method is invoked when frame changed its layout and subviews were this re-layout. In this method you can reset the view controls to set for the new layout. However, with iOS 6 and later we do not need this. AutoLayout take care of these layout changes and we can add constraints to the application and this will happen automatically. 

didReceiveMemoryWarning

- (void)didReceiveMemoryWarning

This method is rarely called. But if you are doing memory consuming tasks in your application like playing with the large images or playing sounds etc. than you should consider handling this method. To avoid memory warning anything which is memory consuming and can be recreated should be released means you should set the pointer to nil.

Note: Remember you never know what is the amount of memory available to your application and you should always keep your memory usage to as low as you can. You should not write you code considering you get lot of memory in the heap.



Below Display LifeCycle Method and Which is time to use specific Method


  • ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work.
  • ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.
  • ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.
  • ViewWill/DidDisappear - Same idea as WillAppear.
  • ViewDidUnload/ViewDidDispose - In Objective C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.

These is no unload anymore.... and thats it... Thats the lifecycle of the view controller.

Keep reading and Commenting....

Happy Coding!!!

Thursday, November 26, 2015

Share and login Facebook

Share and login Facebook

add  the Facebook sdk   in our project

 add FacebookAppID in property list


                                                           In Appdelegate.h


#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strongnonatomicUIWindow *window;
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error;
- (void)userLoggedIn;
- (void)userLoggedOut;


@end


                                                              In Appdelegate.m



//
//  AppDelegate.m
//  shareAndLoginFB
//
//  Created by Regius on 11/09/14.
//  Copyright (c) 2014 Regius. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Load the FBLoginView class (needed for login)
       [FBLoginView class];
    
    // Load the FBProfilePictureView
    // You can find more information about why you need to add this line of code in our troubleshooting guide
    [FBProfilePictureView class];

    // Override point for customization after application launch.
    
    // Whenever a person opens the app, check for a cached session
    if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
        NSLog(@"Found a cached session");
        // If there's one, just open the session silently, without showing the user the login UI
        [FBSession openActiveSessionWithReadPermissions:@[@"basic_info"]
                                           allowLoginUI:NO
                                      completionHandler:^(FBSession *session, FBSessionStatestate, NSError *error) {
                                          // Handler for session state changes
                                          // This method will be called EACH time the session state changes,
                                          // also for intermediate states and NOT just when the session open
                                          [self sessionStateChanged:session state:state error:error];
                                      }];
        
        // If there's no cached session, we will show a login button
    } else {
        NSLog(@"not login inFB");
    }

    return YES;
}
// This method will handle ALL the session state changes in the app
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
    // If the session was opened successfully
    if (!error && state == FBSessionStateOpen){
        NSLog(@"Session opened");
        // Show the user the logged-in UI
        [self userLoggedIn];
        return;
    }
    if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
        // If the session is closed
        NSLog(@"Session closed");
        // Show the user the logged-out UI
        [self userLoggedOut];
    }
    
    // Handle errors
    if (error){
        NSLog(@"Error");
        NSString *alertText;
        NSString *alertTitle;
        // If the error requires people using an app to make an action outside of the app in order to recover
        if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
            alertTitle = @"Something went wrong";
            alertText = [FBErrorUtility userMessageForError:error];
            [self showMessage:alertText withTitle:alertTitle];
        } else {
            
            // If the user cancelled login, do nothing
            if ([FBErrorUtility errorCategoryForError:error] ==FBErrorCategoryUserCancelled) {
                NSLog(@"User cancelled login");
                
                // Handle session closures that happen outside of the app
            } else if ([FBErrorUtility errorCategoryForError:error] ==FBErrorCategoryAuthenticationReopenSession){
                alertTitle = @"Session Error";
                alertText = @"Your current session is no longer valid. Please log in again.";
                [self showMessage:alertText withTitle:alertTitle];
                
                // For simplicity, here we just show a generic message for all other errors
                // You can learn how to handle other errors using our guide:https://developers.facebook.com/docs/ios/errors
            } else {
                //Get more error information from the error
                NSDictionary *errorInformation = [[[error.userInfoobjectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"]objectForKey:@"body"objectForKey:@"error"];
                
                // Show the user an error message
                alertTitle = @"Something went wrong";
                alertText = [NSString stringWithFormat:@"Please retry. \n\n If the problem persists contact us and mention this error code: %@", [errorInformationobjectForKey:@"message"]];
                [self showMessage:alertText withTitle:alertTitle];
            }
        }
        // Clear this token
        [FBSession.activeSession closeAndClearTokenInformation];
        // Show the user the logged-out UI
        [self userLoggedOut];
    }
}

// Show the user the logged-out UI
- (void)userLoggedOut
{
      // Confirm logout message
    [self showMessage:@"You're now logged out" withTitle:@""];
}

// Show the user the logged-in UI
- (void)userLoggedIn
{
    // Set the button title as "Log out"
    
    
    // Welcome message
    [self showMessage:@"You're now logged in" withTitle:@"Welcome!"];
    
}

// Show an alert message
- (void)showMessage:(NSString *)text withTitle:(NSString *)title
{
    [[[UIAlertView allocinitWithTitle:title
                                message:text
                               delegate:self
                      cancelButtonTitle:@"OK!"
                      otherButtonTitles:nilshow];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [FBSession.activeSession handleOpenURL:url];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [FBAppCall handleDidBecomeActive];
}

                                               In yourVIewController.h


#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
@interface ViewController : UIViewController<FBLoginViewDelegate>
-(IBAction)shareWithFB:(id)sender;
-(IBAction)loginWithFB:(id)sender;




                                      In yourVIewController.m
                    #pragma mark login with FB method
-(IBAction)loginWithFB:(id)sender
{
    // If the session state is any of the two "open" states when the button is clicked
    if (FBSession.activeSession.state == FBSessionStateOpen
        || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
        
        // Close the session and remove the access token from the cache
        // The session state handler (in the app delegate) will be called automatically
        [FBSession.activeSession closeAndClearTokenInformation];
        
        // If the session state is not any of the two "open" states when the button is clicked
    } else {
        // Open a session showing the user the login UI
        // You must ALWAYS ask for basic_info permissions when opening a session
        [FBSessionopenActiveSessionWithReadPermissions:@[@"public_profile",@"user_friends"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {
             
             // Retrieve the app delegate
             AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
             // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
             [appDelegate sessionStateChanged:session state:state error:error];
             
             
             [[FBRequest requestForMestartWithCompletionHandler:
              ^(FBRequestConnection *connection,
                NSDictionary<FBGraphUser> *user,
                NSError *error) {
                  if (!error) {
                      NSString *firstName = user.first_name;
                      NSString *lastName = user.last_name;
                      NSString *facebookId = user.id;
                      NSString *email = [user objectForKey:@"email"];
                      NSString *imageUrl = [[NSString allocinitWithFormat:@"http://graph.facebook.com/%@/picture?type=large", facebookId];
                      NSLog(@"%@",email);
                  }
              }];
         }];
    }
}









-(IBAction)shareWithFB:(id)sender
{
    // Check if the Facebook app is installed and we can present the share dialog
    FBShareDialogParams *params = [[FBShareDialogParams allocinit];
    params.link = [NSURLURLWithString:@"https://developers.facebook.com/docs/ios/share/"];
    params.name = @"Sharing Tutorial";
    params.caption = @"Build great social apps and get more installs.";
    params.picture = [NSURL URLWithString:@"http://i.imgur.com/g3Qc1HN.png"];
    params.description = @"Allow your users to share stories on Facebook from your app using the iOS SDK.";
    
    
    // If the Facebook app is installed and we can present the share dialog
    if ([FBDialogs canPresentShareDialogWithParams:params]) {
        
        // Present share dialog
        [FBDialogs presentShareDialogWithLink:params.link
                                         name:params.name
                                      caption:params.caption
                                  description:params.description
                                      picture:params.picture
                                  clientState:nil
                                      handler:^(FBAppCall *call, NSDictionary *results, NSError*error) {
                                          if(error) {
                                              // An error occurred, we need to handle the error
                                              // See: https://developers.facebook.com/docs/ios/errors
                                              NSLog([NSString stringWithFormat:@"Error publishing story: %@", error.description]);
                                          } else {
                                              // Success
                                              NSLog(@"result %@", results);
                                          }
                                      }];
        
        // If the Facebook app is NOT installed and we can't present the share dialog
    } else {
        // FALLBACK: publish just a link using the Feed dialog
        
        // Put together the dialog parameters
        NSMutableDictionary *params = [NSMutableDictionarydictionaryWithObjectsAndKeys:
                                       @"Sharing Tutorial"@"name",
                                       @"Build great social apps and get more installs."@"caption",
                                       @"Allow your users to share stories on Facebook from your app using the iOS SDK."@"description",
                                       @"https://developers.facebook.com/docs/ios/share/"@"link",
                                       @"http://i.imgur.com/g3Qc1HN.png"@"picture",
                                       nil];
        
        // Show the feed dialog
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:params
                                                  handler:^(FBWebDialogResult result, NSURL*resultURL, NSError *error) {
                                                      if (error) {
                                                          // An error occurred, we need to handle the error
                                                          // See:https://developers.facebook.com/docs/ios/errors
                                                          NSLog([NSString stringWithFormat:@"Error publishing story: %@", error.description]);
                                                      } else {
                                                          if (result ==FBWebDialogResultDialogNotCompleted) {
                                                              // User canceled.
                                                              NSLog(@"User cancelled.");
                                                          } else {
                                                              // Handle the publish feed callback
                                                              NSDictionary *urlParams = [selfparseURLParams:[resultURL query]];
                                                              
                                                              if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User canceled.
                                                                  NSLog(@"User cancelled.");
                                                                  
                                                              } else {
                                                                  // User clicked the Share button
                                                                  NSString *result = [NSStringstringWithFormat@"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                  NSLog(@"result %@", result);
                                                              }
                                                          }
                                                      }
                                                  }];
    }

    
    
    
    
}


// A function for parsing URL parameters returned by the Feed Dialog.
- (NSDictionary*)parseURLParams:(NSString *)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary allocinit];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val =
        [kv[1stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        params[kv[0]] = val;
    }
    return params;
}