Download Facebook SDK from following link- https://developers.facebook.com/docs/ios
Add SDK to your project. This code will help you login and get user data as well fetch friend list from specific account.
FBManager - Create a file and write the following content in FBManager.h
- #import <Foundation/Foundation.h>
- #import <FacebookSDK/FacebookSDK.h>
- @interface MyFBManager : NSObject{
- void (^completionBlock)(id data, BOOL success);
- }
- + (MyFBManager *)sharedManager;
- - (void)loginToFB:(void(^)(id data, BOOL result))block;
- - (void)getUserBasicData:(void(^)(id userValue, BOOL result))block;
- - (void)getMyFBFriends:(void(^)(id friends, BOOL result))block;
- - (void)getMyFBPictures:(void(^)(id data, BOOL result))block;
- - (BOOL)isAlreadyLoggedIn;
- - (void)logoutFromFB:(void(^)(id data, BOOL result))block;
- @end
FBManager.m
- #import "MyFBManager.h"
- @implementation MyFBManager
- static MyFBManager *myFBManager = nil;
- + (MyFBManager *)sharedManager{
- if (!myFBManager) {
- myFBManager = [[MyFBManager alloc]init];
- }
- return myFBManager;
- }
- - (BOOL)isAlreadyLoggedIn{
- return [FBSession activeSession].accessTokenData.accessToken.length?YES:NO;
- }
- - (void)loginToFB:(void(^)(id data, BOOL result))block{
- NSLog(@"Login in to FB");
- if ([[FBSession activeSession] isOpen]) {
- NSLog(@"session is active");
- block([FBSession activeSession].accessTokenData.accessToken, YES);
- }
- else{
- [FBSession openActiveSessionWithReadPermissions:[NSArray arrayWithObjects:@"email",@"user_location",@"user_groups", nil] allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
- if (error) {
- NSLog(@"errror==%ld==%@",(long)error.code,error.debugDescription);
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
- message:error.localizedDescription
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
- // if otherwise we check to see if the session is open, an alternative to
- // to the FB_ISSESSIONOPENWITHSTATE helper-macro would be to check the isOpen
- // property of the session object; the macros are useful, however, for more
- // detailed state checking for FBSession objects
- block(nil, YES);
- } else if (FB_ISSESSIONOPENWITHSTATE(status)) {
- // send our requests if we successfully logged in
- // [self sendRequests];
- NSLog(@"access token is== %@", session.accessTokenData.accessToken);
- block(session.accessTokenData.accessToken, YES);
- }
- }];
- }
- }
- - (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
- {
- // If the session was opened successfully
- if (!error && state == FBSessionStateOpen){
- NSLog(@"Session opened");
- // [self getUserBasicData];
- 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.userInfo objectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:@"body"] objectForKey:@"error"];
- // Show the user an error message
- }
- }
- // Clear this token
- [FBSession.activeSession closeAndClearTokenInformation];
- // Show the user the logged-out UI
- // [self userLoggedOut];
- }
- }
- -(void)getUserBasicData:(void(^)(id userValue, BOOL result))block
- {
- NSLog(@"getting details here");
- if (![[FBSession activeSession] isOpen]){
- [[[UIAlertView alloc]initWithTitle:@"Please Login" message:@"Login to FB first" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
- block(nil, NO);
- return;
- }
- [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
- {
- block(result, error?NO:YES);
- }];
- }
- - (void)getMyFBFriends:(void(^)(id friends, BOOL result))block{
- [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
- block(result, error?NO:YES);
- }];
- }
- - (void)uploadTheImageToFB:(UIImage *)image withTitle:(NSString *)title description:(NSString *)description completionBlock:(void(^)(id responseData, BOOL result))block{
- // Uploading image to user's photos on Facebook
- NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[FBSession activeSession].accessTokenData.accessToken,@"access_token",description, @"message",nil];
- if (image) {
- [params setObject:image forKey:@"source"];
- }
- [FBSession setActiveSession:[FBSession activeSession]];
- [FBRequestConnection startWithGraphPath:@"me/photos"
- parameters:params HTTPMethod:@"POST"
- completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
- block(result, error?NO:YES);
- }];
- }
- - (void)getMyFBPictures:(void(^)(id data, BOOL result))block{
- [FBRequestConnection startWithGraphPath:@"/me/photos"
- parameters:nil
- HTTPMethod:@"GET"
- completionHandler:^(
- FBRequestConnection *connection,
- id result,
- NSError *error
- ) {
- block(result, error?NO:YES);
- }];
- }
- -(void)getMyFBGroups:(void (^)(id, BOOL))block
- {
- if (![[FBSession activeSession] isOpen]){
- [[[UIAlertView alloc]initWithTitle:@"Please Login" message:@"Login to FB first" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
- block(nil, NO);
- return;
- }
- [FBRequestConnection startWithGraphPath:@"/me/groups"
- parameters:nil
- HTTPMethod:@"GET"
- completionHandler:^(
- FBRequestConnection *connection,
- id result,
- NSError *error
- ) {
- NSLog(@"result %@",result);
- block(result,error?NO:YES);
- }];
- }
- -(void)getFacebookGroupDetail:(NSString *)groupId completionBlock:(void(^)(id responseData, BOOL result))block
- {
- NSString *str=[NSString stringWithFormat:@"/%@/members",groupId];
- [FBRequestConnection startWithGraphPath:str
- parameters:nil
- HTTPMethod:@"GET"
- completionHandler:^(
- FBRequestConnection *connection,
- id result,
- NSError *error
- ) {
- block(result,error?NO:YES);
- /* handle the result */
- }];
- }
- - (void)logoutFromFB:(void(^)(id data, BOOL result))block{
- [FBSession.activeSession closeAndClearTokenInformation];
- block(Nil, YES);
- }
For
such more Blogs you can visit to http://findnerd.com/NerdDigest
No comments:
Post a Comment