Showing posts with label Fb Friends. Show all posts
Showing posts with label Fb Friends. Show all posts

Wednesday, 27 May 2015

Integrate Facebook SDK in iOS

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
  1. #import <Foundation/Foundation.h>
  2. #import <FacebookSDK/FacebookSDK.h>
  3. @interface MyFBManager : NSObject{
  4. void (^completionBlock)(id data, BOOL success);
  5. }
  6. + (MyFBManager *)sharedManager;
  7. - (void)loginToFB:(void(^)(id data, BOOL result))block;
  8. - (void)getUserBasicData:(void(^)(id userValue, BOOL result))block;
  9. - (void)getMyFBFriends:(void(^)(id friends, BOOL result))block;
  10. - (void)getMyFBPictures:(void(^)(id data, BOOL result))block;
  11. - (BOOL)isAlreadyLoggedIn;
  12. - (void)logoutFromFB:(void(^)(id data, BOOL result))block;
  13. @end
FBManager.m
  1. #import "MyFBManager.h"
  2. @implementation MyFBManager
  3. static MyFBManager *myFBManager = nil;
  4. + (MyFBManager *)sharedManager{
  5. if (!myFBManager) {
  6. myFBManager = [[MyFBManager alloc]init];
  7. }
  8. return myFBManager;
  9. }
  10. - (BOOL)isAlreadyLoggedIn{
  11. return [FBSession activeSession].accessTokenData.accessToken.length?YES:NO;
  12. }
  13. - (void)loginToFB:(void(^)(id data, BOOL result))block{
  14. NSLog(@"Login in to FB");
  15. if ([[FBSession activeSession] isOpen]) {
  16. NSLog(@"session is active");
  17. block([FBSession activeSession].accessTokenData.accessToken, YES);
  18. }
  19. else{
  20. [FBSession openActiveSessionWithReadPermissions:[NSArray arrayWithObjects:@"email",@"user&#95;location",@"user&#95;groups", nil] allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
  21. if (error) {
  22. NSLog(@"errror==%ld==%@",(long)error.code,error.debugDescription);
  23. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
  24. message:error.localizedDescription
  25. delegate:nil
  26. cancelButtonTitle:@"OK"
  27. otherButtonTitles:nil];
  28. [alert show];
  29. // if otherwise we check to see if the session is open, an alternative to
  30. // to the FB&#95;ISSESSIONOPENWITHSTATE helper-macro would be to check the isOpen
  31. // property of the session object; the macros are useful, however, for more
  32. // detailed state checking for FBSession objects
  33. block(nil, YES);
  34. } else if (FB&#95;ISSESSIONOPENWITHSTATE(status)) {
  35. // send our requests if we successfully logged in
  36. // [self sendRequests];
  37. NSLog(@"access token is== %@", session.accessTokenData.accessToken);
  38. block(session.accessTokenData.accessToken, YES);
  39. }
  40. }];
  41. }
  42. }
  43. - (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
  44. {
  45. // If the session was opened successfully
  46. if (!error && state == FBSessionStateOpen){
  47. NSLog(@"Session opened");
  48. // [self getUserBasicData];
  49. return;
  50. }
  51. if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
  52. // If the session is closed
  53. NSLog(@"Session closed");
  54. // Show the user the logged-out UI
  55. // [self userLoggedOut];
  56. }
  57. // Handle errors
  58. if (error){
  59. NSLog(@"Error");
  60. NSString *alertText;
  61. NSString *alertTitle;
  62. // If the error requires people using an app to make an action outside of the app in order to recover
  63. if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
  64. alertTitle = @"Something went wrong";
  65. alertText = [FBErrorUtility userMessageForError:error];
  66. // [self showMessage:alertText withTitle:alertTitle];
  67. } else {
  68. // If the user cancelled login, do nothing
  69. if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
  70. NSLog(@"User cancelled login");
  71. // Handle session closures that happen outside of the app
  72. } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession){
  73. alertTitle = @"Session Error";
  74. alertText = @"Your current session is no longer valid. Please log in again.";
  75. // [self showMessage:alertText withTitle:alertTitle];
  76. // For simplicity, here we just show a generic message for all other errors
  77. // You can learn how to handle other errors using our guide: https://developers.facebook.com/docs/ios/errors
  78. } else {
  79. //Get more error information from the error
  80. // NSDictionary *errorInformation = [[[error.userInfo objectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:@"body"] objectForKey:@"error"];
  81. // Show the user an error message
  82. }
  83. }
  84. // Clear this token
  85. [FBSession.activeSession closeAndClearTokenInformation];
  86. // Show the user the logged-out UI
  87. // [self userLoggedOut];
  88. }
  89. }
  90. -(void)getUserBasicData:(void(^)(id userValue, BOOL result))block
  91. {
  92. NSLog(@"getting details here");
  93. if (![[FBSession activeSession] isOpen]){
  94. [[[UIAlertView alloc]initWithTitle:@"Please Login" message:@"Login to FB first" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
  95. block(nil, NO);
  96. return;
  97. }
  98. [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
  99. {
  100. block(result, error?NO:YES);
  101. }];
  102. }
  103. - (void)getMyFBFriends:(void(^)(id friends, BOOL result))block{
  104. [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  105. block(result, error?NO:YES);
  106. }];
  107. }
  108. - (void)uploadTheImageToFB:(UIImage *)image withTitle:(NSString *)title description:(NSString *)description completionBlock:(void(^)(id responseData, BOOL result))block{
  109. // Uploading image to user's photos on Facebook
  110. NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[FBSession activeSession].accessTokenData.accessToken,@"access&#95;token",description, @"message",nil];
  111. if (image) {
  112. [params setObject:image forKey:@"source"];
  113. }
  114. [FBSession setActiveSession:[FBSession activeSession]];
  115. [FBRequestConnection startWithGraphPath:@"me/photos"
  116. parameters:params HTTPMethod:@"POST"
  117. completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  118. block(result, error?NO:YES);
  119. }];
  120. }
  121. - (void)getMyFBPictures:(void(^)(id data, BOOL result))block{
  122. [FBRequestConnection startWithGraphPath:@"/me/photos"
  123. parameters:nil
  124. HTTPMethod:@"GET"
  125. completionHandler:^(
  126. FBRequestConnection *connection,
  127. id result,
  128. NSError *error
  129. ) {
  130. block(result, error?NO:YES);
  131. }];
  132. }
  133. -(void)getMyFBGroups:(void (^)(id, BOOL))block
  134. {
  135. if (![[FBSession activeSession] isOpen]){
  136. [[[UIAlertView alloc]initWithTitle:@"Please Login" message:@"Login to FB first" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
  137. block(nil, NO);
  138. return;
  139. }
  140. [FBRequestConnection startWithGraphPath:@"/me/groups"
  141. parameters:nil
  142. HTTPMethod:@"GET"
  143. completionHandler:^(
  144. FBRequestConnection *connection,
  145. id result,
  146. NSError *error
  147. ) {
  148. NSLog(@"result %@",result);
  149. block(result,error?NO:YES);
  150. }];
  151. }
  152. -(void)getFacebookGroupDetail:(NSString *)groupId completionBlock:(void(^)(id responseData, BOOL result))block
  153. {
  154. NSString *str=[NSString stringWithFormat:@"/%@/members",groupId];
  155. [FBRequestConnection startWithGraphPath:str
  156. parameters:nil
  157. HTTPMethod:@"GET"
  158. completionHandler:^(
  159. FBRequestConnection *connection,
  160. id result,
  161. NSError *error
  162. ) {
  163. block(result,error?NO:YES);
  164. /* handle the result */
  165. }];
  166. }
  167. - (void)logoutFromFB:(void(^)(id data, BOOL result))block{
  168. [FBSession.activeSession closeAndClearTokenInformation];
  169. block(Nil, YES);
  170. }
For such more Blogs you can visit to http://findnerd.com/NerdDigest