FBSessionDelegate 方法未触发

发布于 2024-10-08 17:27:52 字数 1448 浏览 3 评论 0原文

我正在尝试实施最新的 Facebook Connect SDK,但遇到了一些麻烦。由于某种原因,FBSessionDelegate 协议的委托回调未被触发。我已按照 git Facebook 页面上的说明进行操作,并尝试模仿 Facebook 示例应用程序,但没有成功。我在这里要疯了,所以我要发布我的代码,也许有人会看到我错过的一些愚蠢的东西。

#import <Foundation/Foundation.h>
#import "FBConnect.h"

@interface FacebookWrapper : UIViewController <FBSessionDelegate, FBRequestDelegate, FBDialogDelegate>{
 Facebook* _facebook;
 NSArray* _permissions;
}

@property(readonly) Facebook *facebook;

- (void)login;

@end

#import "FacebookWrapper.h"

static NSString* kAppId = @"1234455667778";

@implementation FacebookWrapper

@synthesize facebook = _facebook;

- (id)init {
 if (self = [super init]) {
  _permissions =  [[NSArray arrayWithObjects: @"read_stream", @"offline_access",nil] retain];
  _facebook = [[Facebook alloc] initWithAppId:kAppId];

 }
 return self;
}

- (void)dealloc {
 [_facebook release];
 [_permissions release];
 [super dealloc];
}

- (void)login {
 [_facebook authorize:_permissions delegate:self];
}

- (void)fbDidLogin {
 NSLog(@"Did Log In");
}

- (void)fbDidNotLogin:(BOOL)cancelled {
 NSLog(@"Failed to log in");
}

- (void)fbDidLogout {
 NSLog(@"Logged Out");
}

从另一个班级调用这个,

FacebookWrapper *fw = [[FacebookWrapper alloc] init];
[fw login];

我在电话上看到的行为符合预期。 Facebook 应用程序在 init 时启动并请求权限。然后,手机将我的应用程序带回前台,但 FBSessionDelegate 的委托永远不会被触发。我已经使用我的应用程序 ID 在 Facebook 示例应用程序中尝试过此操作,效果很好。我不知道有什么区别。

I'm attempting to implement the latest Facebook Connect SDK and I'm having some troubles. For some reason the delegate callbacks for FBSessionDelegate protocol are not being fired. I've followed the instructions on the git Facebook page and tried to mimic the Facebook sample app but no luck. I'm going crazy here so I'm gonna post my code and maybe somebody will see something silly that I've missed.

#import <Foundation/Foundation.h>
#import "FBConnect.h"

@interface FacebookWrapper : UIViewController <FBSessionDelegate, FBRequestDelegate, FBDialogDelegate>{
 Facebook* _facebook;
 NSArray* _permissions;
}

@property(readonly) Facebook *facebook;

- (void)login;

@end

#import "FacebookWrapper.h"

static NSString* kAppId = @"1234455667778";

@implementation FacebookWrapper

@synthesize facebook = _facebook;

- (id)init {
 if (self = [super init]) {
  _permissions =  [[NSArray arrayWithObjects: @"read_stream", @"offline_access",nil] retain];
  _facebook = [[Facebook alloc] initWithAppId:kAppId];

 }
 return self;
}

- (void)dealloc {
 [_facebook release];
 [_permissions release];
 [super dealloc];
}

- (void)login {
 [_facebook authorize:_permissions delegate:self];
}

- (void)fbDidLogin {
 NSLog(@"Did Log In");
}

- (void)fbDidNotLogin:(BOOL)cancelled {
 NSLog(@"Failed to log in");
}

- (void)fbDidLogout {
 NSLog(@"Logged Out");
}

And to call this from another class,

FacebookWrapper *fw = [[FacebookWrapper alloc] init];
[fw login];

The behavior that I'm seeing on the phone is as expected. The Facebook app launches on init and permissions are requested. The phone then brings my app back to the foreground but the delegates for FBSessionDelegate are never fired. I've tried this in the Facebook sample app using my app ID and it worked fine. I have no idea what the difference is.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥抱影子 2024-10-15 17:27:52

我发现了问题所在。在App Delegate中,您需要覆盖handleOpenURL。

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[facebookWrapper facebook] handleOpenURL:url];
}

如果您像我一样创建一个包装类,您将需要在应用程序委托中拥有它的一个实例,以便您可以调用 Facebook 类中的 hanleOpenURL 方法。另请注意,我的 FacebookWrapper 类中的 Facebook 实例有一个公共只读属性,因此我可以调用 handlOpenURL。

通过执行此操作,您的应用程序将知道当它从 Facebook 应用程序内部获取权限返回时要继续到哪里。

I figured out the problem. In the App Delegate you need to override handleOpenURL.

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[facebookWrapper facebook] handleOpenURL:url];
}

If you're creating a wrapper class as I am you'll need an instance of it in the app delegate so you can call the hanleOpenURL method in the Facebook class. Also notice that there is a public readonly property for my Facebook instance in my FacebookWrapper class so I can call handlOpenURL.

By doing this your app will know where to continue when it returns from getting permissions inside of the Facebook app.

合久必婚 2024-10-15 17:27:52

我开发了包装类,这对您非常有帮助。

首先下载Facebook最新的SDK。

创建一个名为“FacebookHelper”的类

在 .h 文件中添加以下代码:

#import <Foundation/Foundation.h>
#import "FBConnect.h"

@protocol FBApiCallDelegate;

typedef enum FBApiCallType
{
FBApiCallNone = 0,
FBApiCallGetUserInfo = 1,
FBApiCallGetUserFriend = 2,
FBApiCallPostMessage = 3,
FBApiCallPostPicture = 4,
FBApiCallShareLink = 5,
FBApiCallPostAll = 6,
FBApiCallPostMessageFriendWall = 7

} FBApiCallType;

@interface FacebookHelper : NSObject<FBRequestDelegate, FBDialogDelegate, FBSessionDelegate> {
Facebook *objFacebook;
NSArray *arrPermission;

id<FBApiCallDelegate> apiCallDelegate;
FBApiCallType currentApiCallType;

NSString *strMessage;
NSString *strUrlTitle;
NSString *strUrl;
NSString *strCaption;
NSString *strPictureUrl;
UIImage *image;
}
@property(readonly) Facebook *objFacebook;

@property (nonatomic, assign) id<FBApiCallDelegate> apiCallDelegate;
@property (nonatomic, assign) FBApiCallType currentApiCallType;

@property (nonatomic, retain) NSString *strMessage;
@property (nonatomic, retain) NSString *strUrlTitle;
@property (nonatomic, retain) NSString *strUrl;
@property (nonatomic, retain) NSString *strCaption;
@property (nonatomic, retain) NSString *strPictureUrl;
@property (nonatomic, retain) UIImage *image;


+ (FacebookHelper *) sharedInstance;
- (void)releaseObjects;

//Store Authentication
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt;
- (void)removeAuthData;

//Public Methods
-(BOOL)isLoggedIn;
-(void)loginToFacebook;
-(void)logoutFromFacebook;

//Facebook Methods
-(void)getUserInfo;                 //Get User Info
-(void)getUserFriends;              //Get User's Friend List
-(void)postMessageToWall;           //Post Message to FB Wall
-(void)postPictureToWall;           //Post Picture to FB Wall
-(void)shareLinkOnWall;             //Share Link on FB Wall
-(void)postAllToWall;               //Post All - Message, Link, Caption, PhotoUrl
-(void)postMessageToFriendWall;     //Post Message to Friend Wall


//String Methods
- (BOOL)isEmptyString:(NSString *)strValue;
- (NSString *) trimWhiteSpace:(NSString *)strValue;

// Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate;

@end

@protocol FBApiCallDelegate <NSObject>

@optional

//Get User Info Delegate
-(void)finishUserInfoResponse:(id)result;
-(void)failedUserInfoResponse:(NSError *)error;

//Get User's Friend List
-(void)finishUserFriendResponse:(id)result;
-(void)failedUserFriendResponse:(NSError *)error;

//Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result;
-(void)failedPostMessageResponse:(NSError *)error;

//Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result;
-(void)failedPostPictureResponse:(NSError *)error;

//Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result;
-(void)failedShareLinkResponse:(NSError *)error;

//Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result;
-(void)failedPostAllResponse:(NSError *)error;

//Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result;
-(void)failedPostMsgFriendWallResponse:(NSError *)error;

@end

在 .m 文件中添加以下代码:

#import "FacebookHelper.h"

@implementation FacebookHelper

@synthesize objFacebook;
@synthesize apiCallDelegate, currentApiCallType;
@synthesize strMessage, strUrlTitle, strUrl, strCaption, strPictureUrl, image;

#pragma mark -
#pragma mark Singleton Variables
static FacebookHelper *singletonHelper = nil;

#pragma mark -
#pragma mark Singleton Methods
- (id)init {
if (!g_kFacebookAppId) {
    NSLog(@"%@", msgFBAppIDMissing);
    exit(1);
    return nil;
}

if ((self = [super init])) {
    arrPermission =  [[NSArray arrayWithObjects: @"read_stream", @"publish_stream", @"offline_access", @"email", @"read_friendlists", @"friends_birthday",nil] retain];
}

return self;
}
+ (FacebookHelper *)sharedInstance {
@synchronized(self) {
    if (singletonHelper == nil) {
        [[self alloc] init]; // assignment not done here
    }
}
return singletonHelper;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
    if (singletonHelper == nil) {
        singletonHelper = [super allocWithZone:zone];
        // assignment and return on first allocation
        return singletonHelper;
    }
}
// on subsequent allocation attempts return nil
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX;  // denotes an object that cannot be released
}
//- (void)release {
- (void)dealloc {
[self releaseObjects];

[super dealloc];
}
- (id)autorelease {
return self;
}
- (void)releaseObjects {
[self.strMessage release];
[self.strUrlTitle release];
[self.strUrl release];
[self.strCaption release];
[self.strPictureUrl release];
[self.image release];

[objFacebook release];
objFacebook = nil;
}

#pragma mark -
#pragma mark FBDelegate(FBSessionDelegate) Methods
/**
 * Called when the user has logged in successfully.
 */
- (void)fbDidLogin {
NSLog(@"FB login OK");
[self storeAuthData:objFacebook.accessToken expiresAt:objFacebook.expirationDate];

switch(currentApiCallType)
{
    case FBApiCallGetUserInfo:
        [self getUserInfo];
        break;
    case FBApiCallGetUserFriend:
        [self getUserFriends];
        break;
    case FBApiCallPostMessage:
        [self postMessageToWall];
        break;
    case FBApiCallPostPicture:
        [self postPictureToWall];
        break;
    case FBApiCallShareLink:
        [self shareLinkOnWall];
        break;
    case FBApiCallPostAll:
        [self postAllToWall];
        break;
    case FBApiCallPostMessageFriendWall:
        [self postMessageToFriendWall];
        break;

}
}
/**
 * Called when the user canceled the authorization dialog.
 */
-(void)fbDidNotLogin:(BOOL)cancelled {
NSLog(@"FB did not login");
[self removeAuthData];
}
/**
 * Called when the request logout has succeeded.
 */
- (void)fbDidLogout { 
NSLog(@"FB logout OK");
[self removeAuthData];
}
-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSLog(@"token extended");
[self storeAuthData:accessToken expiresAt:expiresAt];
}
/**
 * Called when the session has expired.
 */
- (void)fbSessionInvalidated {
[self showAlertView:msgFBSessionInvalidateTitle withMessage:msgFBSessionInvalidateMessage delegate:nil];
[self fbDidLogout];
}

#pragma mark -
#pragma mark FBRequestDelegate Methods
/**
 * Called when the Facebook API request has returned a response. This callback
 * gives you access to the raw response. It's called before
 * (void)request:(FBRequest *)request didLoad:(id)result,
 * which is passed the parsed response object.
 */
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(@"received response");
}
/**
 * Called when a request returns and its response has been parsed into
 * an object. The resulting object may be a dictionary, an array, a string,
 * or a number, depending on the format of the API response. If you need access
 * to the raw response, use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(@"FB request OK");
switch(currentApiCallType)
{
    case FBApiCallGetUserInfo:
        if([self.apiCallDelegate respondsToSelector:@selector(finishUserInfoResponse:)])
            [self.apiCallDelegate finishUserInfoResponse:result];
        break;

    case FBApiCallGetUserFriend:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishUserFriendResponse:)])
            [self.apiCallDelegate finishUserFriendResponse:result];
        break;

    case FBApiCallPostMessage:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostMessageResponse:)])
            [self.apiCallDelegate finishPostMessageResponse:result];
        break;

    case FBApiCallPostPicture:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostPictureResponse:)])
            [self.apiCallDelegate finishPostPictureResponse:result];
        break;

    case FBApiCallShareLink:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishShareLinkResponse:)])
            [self.apiCallDelegate finishShareLinkResponse:result];
        break;

    case FBApiCallPostAll:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostAllResponse:)])
            [self.apiCallDelegate finishPostAllResponse:result];
        break;

    case FBApiCallPostMessageFriendWall:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostMsgFriendWallResponse:)])
            [self.apiCallDelegate finishPostMsgFriendWallResponse:result];
        break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

currentApiCallType = FBApiCallNone;
}
/**
 * Called when an error prevents the Facebook API request from completing
 * successfully.
 */
/*- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(@"FB error: %@", [error localizedDescription]);
}*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(@"Err message: %@", [[error userInfo] objectForKey:@"error_msg"]);
/*NSLog(@"Err code: %@", [error code]);
NSLog(@"Err desc: %@", [error description]);
NSLog(@"FB error: %@", [error localizedDescription]);*/

switch(currentApiCallType)
{
    case FBApiCallGetUserInfo:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedUserInfoResponse:)])
            [self.apiCallDelegate failedUserInfoResponse:error];
        break;

    case FBApiCallGetUserFriend:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedUserFriendResponse:)])
            [self.apiCallDelegate failedUserFriendResponse:error];
        break;

    case FBApiCallPostMessage:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostMessageResponse:)])
            [self.apiCallDelegate failedPostMessageResponse:error];
        break;

    case FBApiCallPostPicture:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostPictureResponse:)])
            [self.apiCallDelegate failedPostPictureResponse:error];
        break;

    case FBApiCallShareLink:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedShareLinkResponse:)])
            [self.apiCallDelegate failedShareLinkResponse:error];
        break;

    case FBApiCallPostAll:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostAllResponse:)])
            [self.apiCallDelegate failedPostAllResponse:error];

    case FBApiCallPostMessageFriendWall:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostMsgFriendWallResponse:)])
            [self.apiCallDelegate failedPostMsgFriendWallResponse:error];
        break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

currentApiCallType = FBApiCallNone;
}
/**
 * Called when a UIServer Dialog successfully return.
 */
- (void)dialogDidComplete:(FBDialog *)dialog {
NSLog(@"Published successfully on FB");
}

#pragma mark -
#pragma mark Store/Remove Authentication 
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:g_kFacebookAccessToken];
[defaults setObject:expiresAt forKey:g_kFacebookExpirationDate];
[defaults synchronize];
}
- (void)removeAuthData{
// Remove saved authorization information if it exists and it is
// ok to clear it (logout, session invalid, app unauthorized)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:g_kFacebookAccessToken];
[defaults removeObjectForKey:g_kFacebookExpirationDate];
[defaults synchronize];

/*
 [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:g_kFacebookAccessToken];
 [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:g_kFacebookExpirationDate];
 [[NSUserDefaults standardUserDefaults] synchronize];*/
/*
 [[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookAccessToken];
 [[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookExpirationDate];
 [[NSUserDefaults standardUserDefaults] synchronize];*/
}

#pragma mark -
#pragma mark Public Methods
-(BOOL)isLoggedIn
{
if(objFacebook == nil)
    objFacebook = [[[Facebook alloc] initWithAppId:g_kFacebookAppId andDelegate:self] retain];

NSString *strAccessToken = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
NSLog(@"Access Token = %@", strAccessToken);

//if(![strAccessToken isEmptyString])
if(![self isEmptyString:strAccessToken])
{
    objFacebook.accessToken    = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
    objFacebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:g_kFacebookExpirationDate];
}

if([objFacebook isSessionValid])
    return YES;
else
    return NO;

return NO;
}
-(void)loginToFacebook
{
if(![self isLoggedIn])
    [objFacebook authorize:arrPermission];
}
-(void)logoutFromFacebook {
[objFacebook logout:self];

[self removeAuthData];
[self releaseObjects];
}

#pragma mark -
#pragma mark Facebook Methods
-(void)getUserInfo
{
currentApiCallType = FBApiCallGetUserInfo;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"name,picture",@"fields",nil];
    [objFacebook requestWithGraphPath:@"me" andParams:params andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)getUserFriends
{
currentApiCallType = FBApiCallGetUserFriend;
if([self isLoggedIn])
{   
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"picture,id,name,birthday,link,gender,last_name,first_name",@"fields",nil];
    [objFacebook requestWithGraphPath:@"me/friends" andParams:params andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postMessageToWall
{
currentApiCallType = FBApiCallPostMessage;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:@"status" forKey:@"type"];
    [params setObject:self.strMessage forKey:@"message"];
    [objFacebook requestWithGraphPath:@"me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postPictureToWall
{
currentApiCallType = FBApiCallPostPicture;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:self.image forKey:@"source"];
    [params setObject:self.strMessage forKey:@"message"];
    [objFacebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)shareLinkOnWall
{
currentApiCallType = FBApiCallShareLink;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:@"link" forKey:@"type"];
    [params setObject:self.strUrl forKey:@"link"];
    [params setObject:self.strMessage forKey:@"description"];
    [objFacebook requestWithGraphPath:@"me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postAllToWall
{
currentApiCallType = FBApiCallPostAll;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:self.strMessage forKey:@"description"];
    [params setObject:self.strUrlTitle forKey:@"name"];
    [params setObject:self.strUrl forKey:@"link"];
    [params setObject:self.strCaption forKey:@"caption"];
    [params setObject:self.strPictureUrl forKey:@"picture"];
    [objFacebook requestWithGraphPath:@"me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postMessageToFriendWall
{
currentApiCallType = FBApiCallPostMessageFriendWall;
if([self isLoggedIn])
{
    NSString *strGraphPath = [NSString stringWithFormat:@"%@/feed", @"100002305497328"];
    //NSString *strGraphPath = [NSString stringWithFormat:@"%@/feed", @"100002560928461"];

    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:self.strMessage forKey:@"message"];
    [objFacebook requestWithGraphPath:strGraphPath andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}

#pragma mark -
#pragma mark String Methods
- (BOOL)isEmptyString:(NSString *)strValue
{   
NSString *copy;

if (strValue == nil)
    return (YES);

if ([strValue isEqualToString:@""])
    return (YES);

if ([strValue isEqualToString:@"(null)"])
    return (YES);

copy = [[strValue copy] autorelease];

//if ([[copy trimWhiteSpace] isEqualToString: @""])
if ([[self trimWhiteSpace:copy] isEqualToString: @""])
    return (YES);

return (NO);
} /*stringIsEmpty*/
- (NSString *) trimWhiteSpace:(NSString *)strValue 
{
NSMutableString *s = [[strValue mutableCopy] autorelease];
CFStringTrimWhitespace ((CFMutableStringRef) s);
return (NSString *) [[s copy] autorelease];
} /*trimWhiteSpace*/

#pragma mark -
#pragma mark Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:pstrTitle message:pstrMessage delegate:pDelegate cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];    
}

@end

就是这样。现在我们的 Facebook 包装类已准备就绪。

创建 3 个以下类以更好地组织。

FacebookGlobal.h

添加以下数据:

#define g_kFacebookAppId        @"<Your AppID>"
#define g_kFacebookAppSecret    @"<Your Secret>"


#define g_kPostMessage          @"<Message>"
#define g_kPostUrlTitle         @"<Title>"
#define g_kPostUrl              @"<Url>"
#define g_kPostCaption          @"<Caption>"
#define g_kPostPictureUrl       @"<Image Url>"

FacebookKey.h

添加以下数据:

#define g_kFacebookAccessToken      @"FBAccessTokenKey"
#define g_kFacebookExpirationDate   @"FBExpirationDateKey"

FacebookMes​​sage.h

添加以下数据:

//AppID Missing 
#define msgFBAppIDMissing @"Missing AppID"

//Session Invalidated
#define msgFBSessionInvalidateTitle @"Auth Exception"
#define msgFBSessionInvalidateMessage @"Your session has expired."

将以下文件导入到您的 .pch 文件中:

#import "FacebookGlobal.h"
#import "FacebookKey.h"
#import "FacebookMessage.h"

#import "FacebookHelper.h"

现在,您就可以使用了。

在您的视图控制器中,添加以下委托:

<FBApiCallDelegate>

在您的视图控制器 .m 文件中,添加以下方法来调用以及委托:

- (void)viewWillAppear:(BOOL)animated {
/*
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
[fbHelper logoutFromFacebook];
*/


//Get User Info
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserInfo];


/*
//Get User's Friend List
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserFriends];
*/

/*
//Post Message to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToWall];
*/

/*
//Post Picture to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.image = [UIImage imageNamed:@"postPicture.jpg"];
[fbHelper postPictureToWall];
*/

/*
//Share Link on FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strMessage = g_kPostMessage;
[fbHelper shareLinkOnWall];
*/

/*
//Post All to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.strUrlTitle = g_kPostUrlTitle;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strCaption = g_kPostCaption;
fbHelper.strPictureUrl = g_kPostPictureUrl;
[fbHelper postAllToWall];
 */

/*
//Post Message to Friend Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToFriendWall];
*/
}



#pragma mark -
#pragma mark Get User Info Delegate
-(void)finishUserInfoResponse:(id)result{
NSLog(@"UserInfo response successed!");
NSLog(@"%@", result);

}
-(void)failedUserInfoResponse:(NSError *)error{
NSLog(@"UserInfo response failed!");
}

#pragma mark -
#pragma mark Get User's Friend List
-(void)finishUserFriendResponse:(id)result{
NSLog(@"User FriendList response successed!");
NSLog(@"%@", result);
}
-(void)failedUserFriendResponse:(NSError *)error{
NSLog(@"User FriendList response failed!");
}

#pragma mark -
#pragma mark Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result{
NSLog(@"Post message successed!");
NSLog(@"%@", result);
}
-(void)failedPostMessageResponse:(NSError *)error{
NSLog(@"Post message failed!");
}

#pragma mark -
#pragma mark Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result{
NSLog(@"Post picture successed!");
NSLog(@"%@", result);
}
-(void)failedPostPictureResponse:(NSError *)error{
NSLog(@"Post picture failed!");
}

#pragma mark -
#pragma mark Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result{
NSLog(@"Share link successed!");
NSLog(@"%@", result);
}
-(void)failedShareLinkResponse:(NSError *)error{
NSLog(@"Share link failed!");
}

#pragma mark -
#pragma mark Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result{
NSLog(@"Post all successed!");
NSLog(@"%@", result);
}
-(void)failedPostAllResponse:(NSError *)error{
NSLog(@"Post all failed!");
}

#pragma mark -
#pragma mark Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result{
NSLog(@"Post message to friend wall successed!");
NSLog(@"%@", result);
}
-(void)failedPostMsgFriendWallResponse:(NSError *)error{
NSLog(@"Post message to friend wall failed!");
}

快乐编码:)

享受吧。

I have developed wrapper class which will be very helpful to you.

First download latest SDK of Facebook.

Create one class named as "FacebookHelper"

Add following code in .h file:

#import <Foundation/Foundation.h>
#import "FBConnect.h"

@protocol FBApiCallDelegate;

typedef enum FBApiCallType
{
FBApiCallNone = 0,
FBApiCallGetUserInfo = 1,
FBApiCallGetUserFriend = 2,
FBApiCallPostMessage = 3,
FBApiCallPostPicture = 4,
FBApiCallShareLink = 5,
FBApiCallPostAll = 6,
FBApiCallPostMessageFriendWall = 7

} FBApiCallType;

@interface FacebookHelper : NSObject<FBRequestDelegate, FBDialogDelegate, FBSessionDelegate> {
Facebook *objFacebook;
NSArray *arrPermission;

id<FBApiCallDelegate> apiCallDelegate;
FBApiCallType currentApiCallType;

NSString *strMessage;
NSString *strUrlTitle;
NSString *strUrl;
NSString *strCaption;
NSString *strPictureUrl;
UIImage *image;
}
@property(readonly) Facebook *objFacebook;

@property (nonatomic, assign) id<FBApiCallDelegate> apiCallDelegate;
@property (nonatomic, assign) FBApiCallType currentApiCallType;

@property (nonatomic, retain) NSString *strMessage;
@property (nonatomic, retain) NSString *strUrlTitle;
@property (nonatomic, retain) NSString *strUrl;
@property (nonatomic, retain) NSString *strCaption;
@property (nonatomic, retain) NSString *strPictureUrl;
@property (nonatomic, retain) UIImage *image;


+ (FacebookHelper *) sharedInstance;
- (void)releaseObjects;

//Store Authentication
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt;
- (void)removeAuthData;

//Public Methods
-(BOOL)isLoggedIn;
-(void)loginToFacebook;
-(void)logoutFromFacebook;

//Facebook Methods
-(void)getUserInfo;                 //Get User Info
-(void)getUserFriends;              //Get User's Friend List
-(void)postMessageToWall;           //Post Message to FB Wall
-(void)postPictureToWall;           //Post Picture to FB Wall
-(void)shareLinkOnWall;             //Share Link on FB Wall
-(void)postAllToWall;               //Post All - Message, Link, Caption, PhotoUrl
-(void)postMessageToFriendWall;     //Post Message to Friend Wall


//String Methods
- (BOOL)isEmptyString:(NSString *)strValue;
- (NSString *) trimWhiteSpace:(NSString *)strValue;

// Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate;

@end

@protocol FBApiCallDelegate <NSObject>

@optional

//Get User Info Delegate
-(void)finishUserInfoResponse:(id)result;
-(void)failedUserInfoResponse:(NSError *)error;

//Get User's Friend List
-(void)finishUserFriendResponse:(id)result;
-(void)failedUserFriendResponse:(NSError *)error;

//Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result;
-(void)failedPostMessageResponse:(NSError *)error;

//Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result;
-(void)failedPostPictureResponse:(NSError *)error;

//Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result;
-(void)failedShareLinkResponse:(NSError *)error;

//Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result;
-(void)failedPostAllResponse:(NSError *)error;

//Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result;
-(void)failedPostMsgFriendWallResponse:(NSError *)error;

@end

Add following code in .m file:

#import "FacebookHelper.h"

@implementation FacebookHelper

@synthesize objFacebook;
@synthesize apiCallDelegate, currentApiCallType;
@synthesize strMessage, strUrlTitle, strUrl, strCaption, strPictureUrl, image;

#pragma mark -
#pragma mark Singleton Variables
static FacebookHelper *singletonHelper = nil;

#pragma mark -
#pragma mark Singleton Methods
- (id)init {
if (!g_kFacebookAppId) {
    NSLog(@"%@", msgFBAppIDMissing);
    exit(1);
    return nil;
}

if ((self = [super init])) {
    arrPermission =  [[NSArray arrayWithObjects: @"read_stream", @"publish_stream", @"offline_access", @"email", @"read_friendlists", @"friends_birthday",nil] retain];
}

return self;
}
+ (FacebookHelper *)sharedInstance {
@synchronized(self) {
    if (singletonHelper == nil) {
        [[self alloc] init]; // assignment not done here
    }
}
return singletonHelper;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
    if (singletonHelper == nil) {
        singletonHelper = [super allocWithZone:zone];
        // assignment and return on first allocation
        return singletonHelper;
    }
}
// on subsequent allocation attempts return nil
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX;  // denotes an object that cannot be released
}
//- (void)release {
- (void)dealloc {
[self releaseObjects];

[super dealloc];
}
- (id)autorelease {
return self;
}
- (void)releaseObjects {
[self.strMessage release];
[self.strUrlTitle release];
[self.strUrl release];
[self.strCaption release];
[self.strPictureUrl release];
[self.image release];

[objFacebook release];
objFacebook = nil;
}

#pragma mark -
#pragma mark FBDelegate(FBSessionDelegate) Methods
/**
 * Called when the user has logged in successfully.
 */
- (void)fbDidLogin {
NSLog(@"FB login OK");
[self storeAuthData:objFacebook.accessToken expiresAt:objFacebook.expirationDate];

switch(currentApiCallType)
{
    case FBApiCallGetUserInfo:
        [self getUserInfo];
        break;
    case FBApiCallGetUserFriend:
        [self getUserFriends];
        break;
    case FBApiCallPostMessage:
        [self postMessageToWall];
        break;
    case FBApiCallPostPicture:
        [self postPictureToWall];
        break;
    case FBApiCallShareLink:
        [self shareLinkOnWall];
        break;
    case FBApiCallPostAll:
        [self postAllToWall];
        break;
    case FBApiCallPostMessageFriendWall:
        [self postMessageToFriendWall];
        break;

}
}
/**
 * Called when the user canceled the authorization dialog.
 */
-(void)fbDidNotLogin:(BOOL)cancelled {
NSLog(@"FB did not login");
[self removeAuthData];
}
/**
 * Called when the request logout has succeeded.
 */
- (void)fbDidLogout { 
NSLog(@"FB logout OK");
[self removeAuthData];
}
-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSLog(@"token extended");
[self storeAuthData:accessToken expiresAt:expiresAt];
}
/**
 * Called when the session has expired.
 */
- (void)fbSessionInvalidated {
[self showAlertView:msgFBSessionInvalidateTitle withMessage:msgFBSessionInvalidateMessage delegate:nil];
[self fbDidLogout];
}

#pragma mark -
#pragma mark FBRequestDelegate Methods
/**
 * Called when the Facebook API request has returned a response. This callback
 * gives you access to the raw response. It's called before
 * (void)request:(FBRequest *)request didLoad:(id)result,
 * which is passed the parsed response object.
 */
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(@"received response");
}
/**
 * Called when a request returns and its response has been parsed into
 * an object. The resulting object may be a dictionary, an array, a string,
 * or a number, depending on the format of the API response. If you need access
 * to the raw response, use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(@"FB request OK");
switch(currentApiCallType)
{
    case FBApiCallGetUserInfo:
        if([self.apiCallDelegate respondsToSelector:@selector(finishUserInfoResponse:)])
            [self.apiCallDelegate finishUserInfoResponse:result];
        break;

    case FBApiCallGetUserFriend:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishUserFriendResponse:)])
            [self.apiCallDelegate finishUserFriendResponse:result];
        break;

    case FBApiCallPostMessage:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostMessageResponse:)])
            [self.apiCallDelegate finishPostMessageResponse:result];
        break;

    case FBApiCallPostPicture:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostPictureResponse:)])
            [self.apiCallDelegate finishPostPictureResponse:result];
        break;

    case FBApiCallShareLink:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishShareLinkResponse:)])
            [self.apiCallDelegate finishShareLinkResponse:result];
        break;

    case FBApiCallPostAll:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostAllResponse:)])
            [self.apiCallDelegate finishPostAllResponse:result];
        break;

    case FBApiCallPostMessageFriendWall:
        if ([self.apiCallDelegate respondsToSelector:@selector(finishPostMsgFriendWallResponse:)])
            [self.apiCallDelegate finishPostMsgFriendWallResponse:result];
        break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

currentApiCallType = FBApiCallNone;
}
/**
 * Called when an error prevents the Facebook API request from completing
 * successfully.
 */
/*- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(@"FB error: %@", [error localizedDescription]);
}*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(@"Err message: %@", [[error userInfo] objectForKey:@"error_msg"]);
/*NSLog(@"Err code: %@", [error code]);
NSLog(@"Err desc: %@", [error description]);
NSLog(@"FB error: %@", [error localizedDescription]);*/

switch(currentApiCallType)
{
    case FBApiCallGetUserInfo:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedUserInfoResponse:)])
            [self.apiCallDelegate failedUserInfoResponse:error];
        break;

    case FBApiCallGetUserFriend:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedUserFriendResponse:)])
            [self.apiCallDelegate failedUserFriendResponse:error];
        break;

    case FBApiCallPostMessage:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostMessageResponse:)])
            [self.apiCallDelegate failedPostMessageResponse:error];
        break;

    case FBApiCallPostPicture:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostPictureResponse:)])
            [self.apiCallDelegate failedPostPictureResponse:error];
        break;

    case FBApiCallShareLink:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedShareLinkResponse:)])
            [self.apiCallDelegate failedShareLinkResponse:error];
        break;

    case FBApiCallPostAll:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostAllResponse:)])
            [self.apiCallDelegate failedPostAllResponse:error];

    case FBApiCallPostMessageFriendWall:
        if ([self.apiCallDelegate respondsToSelector:@selector(failedPostMsgFriendWallResponse:)])
            [self.apiCallDelegate failedPostMsgFriendWallResponse:error];
        break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

currentApiCallType = FBApiCallNone;
}
/**
 * Called when a UIServer Dialog successfully return.
 */
- (void)dialogDidComplete:(FBDialog *)dialog {
NSLog(@"Published successfully on FB");
}

#pragma mark -
#pragma mark Store/Remove Authentication 
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:g_kFacebookAccessToken];
[defaults setObject:expiresAt forKey:g_kFacebookExpirationDate];
[defaults synchronize];
}
- (void)removeAuthData{
// Remove saved authorization information if it exists and it is
// ok to clear it (logout, session invalid, app unauthorized)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:g_kFacebookAccessToken];
[defaults removeObjectForKey:g_kFacebookExpirationDate];
[defaults synchronize];

/*
 [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:g_kFacebookAccessToken];
 [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:g_kFacebookExpirationDate];
 [[NSUserDefaults standardUserDefaults] synchronize];*/
/*
 [[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookAccessToken];
 [[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookExpirationDate];
 [[NSUserDefaults standardUserDefaults] synchronize];*/
}

#pragma mark -
#pragma mark Public Methods
-(BOOL)isLoggedIn
{
if(objFacebook == nil)
    objFacebook = [[[Facebook alloc] initWithAppId:g_kFacebookAppId andDelegate:self] retain];

NSString *strAccessToken = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
NSLog(@"Access Token = %@", strAccessToken);

//if(![strAccessToken isEmptyString])
if(![self isEmptyString:strAccessToken])
{
    objFacebook.accessToken    = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
    objFacebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:g_kFacebookExpirationDate];
}

if([objFacebook isSessionValid])
    return YES;
else
    return NO;

return NO;
}
-(void)loginToFacebook
{
if(![self isLoggedIn])
    [objFacebook authorize:arrPermission];
}
-(void)logoutFromFacebook {
[objFacebook logout:self];

[self removeAuthData];
[self releaseObjects];
}

#pragma mark -
#pragma mark Facebook Methods
-(void)getUserInfo
{
currentApiCallType = FBApiCallGetUserInfo;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"name,picture",@"fields",nil];
    [objFacebook requestWithGraphPath:@"me" andParams:params andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)getUserFriends
{
currentApiCallType = FBApiCallGetUserFriend;
if([self isLoggedIn])
{   
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"picture,id,name,birthday,link,gender,last_name,first_name",@"fields",nil];
    [objFacebook requestWithGraphPath:@"me/friends" andParams:params andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postMessageToWall
{
currentApiCallType = FBApiCallPostMessage;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:@"status" forKey:@"type"];
    [params setObject:self.strMessage forKey:@"message"];
    [objFacebook requestWithGraphPath:@"me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postPictureToWall
{
currentApiCallType = FBApiCallPostPicture;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:self.image forKey:@"source"];
    [params setObject:self.strMessage forKey:@"message"];
    [objFacebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)shareLinkOnWall
{
currentApiCallType = FBApiCallShareLink;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:@"link" forKey:@"type"];
    [params setObject:self.strUrl forKey:@"link"];
    [params setObject:self.strMessage forKey:@"description"];
    [objFacebook requestWithGraphPath:@"me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postAllToWall
{
currentApiCallType = FBApiCallPostAll;
if([self isLoggedIn])
{
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:self.strMessage forKey:@"description"];
    [params setObject:self.strUrlTitle forKey:@"name"];
    [params setObject:self.strUrl forKey:@"link"];
    [params setObject:self.strCaption forKey:@"caption"];
    [params setObject:self.strPictureUrl forKey:@"picture"];
    [objFacebook requestWithGraphPath:@"me/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}
-(void)postMessageToFriendWall
{
currentApiCallType = FBApiCallPostMessageFriendWall;
if([self isLoggedIn])
{
    NSString *strGraphPath = [NSString stringWithFormat:@"%@/feed", @"100002305497328"];
    //NSString *strGraphPath = [NSString stringWithFormat:@"%@/feed", @"100002560928461"];

    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:self.strMessage forKey:@"message"];
    [objFacebook requestWithGraphPath:strGraphPath andParams:params andHttpMethod:@"POST" andDelegate:self];
}
else
    [self loginToFacebook];
}

#pragma mark -
#pragma mark String Methods
- (BOOL)isEmptyString:(NSString *)strValue
{   
NSString *copy;

if (strValue == nil)
    return (YES);

if ([strValue isEqualToString:@""])
    return (YES);

if ([strValue isEqualToString:@"(null)"])
    return (YES);

copy = [[strValue copy] autorelease];

//if ([[copy trimWhiteSpace] isEqualToString: @""])
if ([[self trimWhiteSpace:copy] isEqualToString: @""])
    return (YES);

return (NO);
} /*stringIsEmpty*/
- (NSString *) trimWhiteSpace:(NSString *)strValue 
{
NSMutableString *s = [[strValue mutableCopy] autorelease];
CFStringTrimWhitespace ((CFMutableStringRef) s);
return (NSString *) [[s copy] autorelease];
} /*trimWhiteSpace*/

#pragma mark -
#pragma mark Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:pstrTitle message:pstrMessage delegate:pDelegate cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];    
}

@end

That's it. Now our Facebook wrapper class is ready.

Create 3 below class for better organization.

FacebookGlobal.h

Add below data:

#define g_kFacebookAppId        @"<Your AppID>"
#define g_kFacebookAppSecret    @"<Your Secret>"


#define g_kPostMessage          @"<Message>"
#define g_kPostUrlTitle         @"<Title>"
#define g_kPostUrl              @"<Url>"
#define g_kPostCaption          @"<Caption>"
#define g_kPostPictureUrl       @"<Image Url>"

FacebookKey.h

Add below data:

#define g_kFacebookAccessToken      @"FBAccessTokenKey"
#define g_kFacebookExpirationDate   @"FBExpirationDateKey"

FacebookMessage.h

Add below data:

//AppID Missing 
#define msgFBAppIDMissing @"Missing AppID"

//Session Invalidated
#define msgFBSessionInvalidateTitle @"Auth Exception"
#define msgFBSessionInvalidateMessage @"Your session has expired."

Import below files in your .pch files:

#import "FacebookGlobal.h"
#import "FacebookKey.h"
#import "FacebookMessage.h"

#import "FacebookHelper.h"

Now, you are ready for use.

In your view controller, add below delegate:

<FBApiCallDelegate>

In your view controller .m file, add below methods to call as well delegate:

- (void)viewWillAppear:(BOOL)animated {
/*
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
[fbHelper logoutFromFacebook];
*/


//Get User Info
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserInfo];


/*
//Get User's Friend List
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserFriends];
*/

/*
//Post Message to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToWall];
*/

/*
//Post Picture to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.image = [UIImage imageNamed:@"postPicture.jpg"];
[fbHelper postPictureToWall];
*/

/*
//Share Link on FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strMessage = g_kPostMessage;
[fbHelper shareLinkOnWall];
*/

/*
//Post All to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.strUrlTitle = g_kPostUrlTitle;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strCaption = g_kPostCaption;
fbHelper.strPictureUrl = g_kPostPictureUrl;
[fbHelper postAllToWall];
 */

/*
//Post Message to Friend Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToFriendWall];
*/
}



#pragma mark -
#pragma mark Get User Info Delegate
-(void)finishUserInfoResponse:(id)result{
NSLog(@"UserInfo response successed!");
NSLog(@"%@", result);

}
-(void)failedUserInfoResponse:(NSError *)error{
NSLog(@"UserInfo response failed!");
}

#pragma mark -
#pragma mark Get User's Friend List
-(void)finishUserFriendResponse:(id)result{
NSLog(@"User FriendList response successed!");
NSLog(@"%@", result);
}
-(void)failedUserFriendResponse:(NSError *)error{
NSLog(@"User FriendList response failed!");
}

#pragma mark -
#pragma mark Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result{
NSLog(@"Post message successed!");
NSLog(@"%@", result);
}
-(void)failedPostMessageResponse:(NSError *)error{
NSLog(@"Post message failed!");
}

#pragma mark -
#pragma mark Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result{
NSLog(@"Post picture successed!");
NSLog(@"%@", result);
}
-(void)failedPostPictureResponse:(NSError *)error{
NSLog(@"Post picture failed!");
}

#pragma mark -
#pragma mark Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result{
NSLog(@"Share link successed!");
NSLog(@"%@", result);
}
-(void)failedShareLinkResponse:(NSError *)error{
NSLog(@"Share link failed!");
}

#pragma mark -
#pragma mark Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result{
NSLog(@"Post all successed!");
NSLog(@"%@", result);
}
-(void)failedPostAllResponse:(NSError *)error{
NSLog(@"Post all failed!");
}

#pragma mark -
#pragma mark Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result{
NSLog(@"Post message to friend wall successed!");
NSLog(@"%@", result);
}
-(void)failedPostMsgFriendWallResponse:(NSError *)error{
NSLog(@"Post message to friend wall failed!");
}

Happy Coding :)

Enjoy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文