在AppDelegate.m中引入
#import <FacebookSDK/FacebookSDK.h>
首先初始化:
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
// Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
// You can add your app-specific url handling code here if needed
return wasHandled;
}
- (void)applicationDidBecomeActive:(UIApplication*)application
{
[FBAppEvents activateApp];
}
配置*.plist
登录验证接入 接口引入FBLoginViewDelegate
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error
{
NSString *alertMessage, *alertTitle;
// If the user should perform an action outside of you app to recover,
// the SDK will provide a message for the user, you just need to surface it.
// This conveniently handles cases like Facebook password change or unverified Facebook accounts.
if ([FBErrorUtility shouldNotifyUserForError:error]) {
alertTitle = @"Facebook error";
alertMessage = [FBErrorUtility userMessageForError:error];
// This code will handle session closures that happen outside of the app
// You can take a look at our error handling guide to know more about it
// https://developers.facebook.com/docs/ios/errors
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
alertTitle = @"Session Error";
alertMessage = @"Your current session is no longer valid. Please log in again.";
// If the user has cancelled a login, we will do nothing.
// You can also choose to show the user a message if cancelling login will result in
// the user not being able to complete a task they had initiated in your app
// (like accessing FB-stored information or posting to Facebook)
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
NSLog(@"user cancelled login");
// For simplicity, this sample handles other errors with a generic message
// You can checkout our error handling guide for more detailed information
// https://developers.facebook.com/docs/ios/errors
} else {
alertTitle = @"Something went wrong";
alertMessage = @"Please try again later.";
NSLog(@"Unexpected error:%@", error);
}
if (alertMessage) {
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user
{
NSLog(@"loginViewFetchedUserInfo");
FBAccessTokenData *accessTokenData = [[FBSession activeSession] accessTokenData];
[[NtModule shared] onLoginSuccess:user.id withToken:[accessTokenData accessToken]];
}
// Logged-in user experience
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView
{
NSLog(@"loginViewShowingLoggedInUser");
}
// Logged-out user experience
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView
{
NSLog(@"loginViewShowingLoggedOutUser");
[[NtModule shared] onLogout];
}
- (void)onLogout
{
// sdk登出后处理内容
}
- (NSString *)md5:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (void)onLoginSuccess:(NSString*)userID withToken:(NSString*)token
{
NSLog(@"onLoginSuccess");
NSLog(@"%@",userID);
NSLog(@"%@",token);
NSLog(@"%@",self.mLoginCallback);
self.mUserID = userID;
self.mToken = token;
NSString *tmpString = [self md5:[NSString stringWithFormat:@"%@%@", userID, [NSString stringWithUTF8String:Key]]];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:userID forKey:@"Username"];
[data setObject:token forKey:@"Password"];
[data setObject:@"" forKey:@"Error"];
[data setObject:[NSString stringWithFormat:@"%@:%@", userID, tmpString] forKey:@"SessionID"];
self.mLoginView.hidden = YES;
UnitySendMessage("NtModule",
[self.mLoginCallback UTF8String],
[[NtModule JSONRepresentation:data] UTF8String]);
}
分享接入:
- (void)fbInvite:(NSString*)title withCallback:(NSString*)text withCallback:(NSString*)data withCallback:(NSString *)link withCallback:(NSString *)picUrl
{
NSLog(@"fbInvite");
NSLog(@"title:%@", title);
NSLog(@"text:%@", text);
NSLog(@"data:%@", data);
NSLog(@"link:%@", link);
NSLog(@"imageUrl:%@", picUrl);
//FBLinkShareParams *param = [[FBLinkShareParams alloc] initWithLink:[NSURL URLWithString:link] name:title caption:text description:data picture:[NSURL URLWithString:picUrl]];
FBLinkShareParams *linkShareParams = [[FBLinkShareParams alloc] init];
linkShareParams.link = [NSURL URLWithString:link];
linkShareParams.name = title;
linkShareParams.caption = text;
linkShareParams.linkDescription = data;
linkShareParams.picture = [NSURL URLWithString:picUrl];
if ([FBDialogs canPresentMessageDialogWithParams:linkShareParams])
{
[FBDialogs presentMessageDialogWithParams:linkShareParams clientState:nil handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(@"%@", error.description);
}else{
NSLog(@"shared success");
}
}];
}
else
{
NSLog(@"can`t shared info...");
NSMutableDictionary *shareParams = [[NSMutableDictionary alloc] init];
[shareParams setObject:link forKey:@"link"];
[shareParams setObject:title forKey:@"name"];
[shareParams setObject:text forKey:@"caption"];
[shareParams setObject:data forKey:@"description"];
[shareParams setObject:picUrl forKey:@"picture"];
[FBWebDialogs presentFeedDialogModallyWithSession:nil parameters:shareParams handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(@"%@", error.description);
}else{
if (result == FBWebDialogResultDialogNotCompleted) {
} else {
// Handle the publish feed callback
NSLog(@"[resultURL query]--:%@", [resultURL query]);
if (![[resultURL query] containsString:@"post_id"]) {
} else {
// User clicked the Share button
}
}
}
}];
}
另外,非弹窗的分享:
//不显示界面,直接发布到自己的facebook主页上
void MTChannelHelp::facebookPublish(string message, string tags, string link, string picture, string name, string caption, string description) {
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
if (!message.empty())
[params setObject:[NSString stringWithUTF8String:message.c_str()] forKey:@"message"];
if (!tags.empty())
[params setObject:[NSString stringWithUTF8String:tags.c_str()] forKey:@"tags"];
if (!link.empty())
[params setObject:[NSString stringWithUTF8String:link.c_str()] forKey:@"link"];
if (!picture.empty())
[params setObject:[NSString stringWithUTF8String:picture.c_str()] forKey:@"picture"];
if (!name.empty())
[params setObject:[NSString stringWithUTF8String:name.c_str()] forKey:@"name"];
if (!caption.empty())
[params setObject:[NSString stringWithUTF8String:caption.c_str()] forKey:@"caption"];
if (!description.empty())
[params setObject:[NSString stringWithUTF8String:description.c_str()] forKey:@"description"];
if (![FBSession.activeSession hasGranted:@"publish_actions"]) {
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:@"publish_actions", nil]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error) {
_facebookPublish(params);
}
else{
_facebookGetPermissionsCallback("publish_actions", [error code], [error.localizedDescription UTF8String]);
}
}];
}
else {
_facebookPublish(params);
}
}
void MTChannelHelp::_facebookPublish(void *parameters) {
NSMutableDictionary *params = (NSMutableDictionary *)parameters;
[FBRequestConnection startWithGraphPath:@"/me/feed"
parameters:params
HTTPMethod:@"POST"
completionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
if (!error) {
NSString *resultID = [result objectForKey:@"id"];
LuaValueDict luaDict;
luaDict["success"] = LuaValue::booleanValue(true);
luaDict["postID"] = LuaValue::stringValue([resultID UTF8String]);
_facebookCallback(FACEBOOK_KEY_PUBLISH, luaDict);
}
else {
LuaValueDict luaDict;
luaDict["success"] = LuaValue::booleanValue(false);
luaDict["errorCode"] = LuaValue::intValue([error code]);
luaDict["errorInfo"] = LuaValue::stringValue([error.localizedDescription UTF8String]);
_facebookCallback(FACEBOOK_KEY_PUBLISH, luaDict);
}
}];
[params release];
}