如何使用Facebook iOS SDK检索Facebook响应 [英] How to retrieve Facebook response using Facebook iOS SDK
问题描述
facebook = [[Facebook alloc] initWithAppId:kAppId];
然后我登录:
[facebook authorize:permissions delegate:self];
登录Facebook后,我正在执行以下操作获取用户个人资料信息:
[facebook requestWithGraphPath:@meandDelegate:self];
NSMutableData * response = [fbRequest responseText];
unsigned char * firstBuffer = [response mutableBytes];
NSLog(@Got Facebook Profile::\%s\\\\
,(char *)firstBuffer);
但是我在控制台上收到以下内容:
收到Facebook个人资料:(null)
我做错了什么,我相信Facebook的响应是一个json字符串,我正在寻找一个json字符串。
我以为可能是应该做一个维基,告诉人们我是怎么做的。因为很多人都面临着类似的问题。
我所做的第一件事就是在Facebook上。
m类我在以下方法中添加了以下语句
(void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth
safariAuth: (BOOL)trySafariAuth
trySafariAuth = NO;
这可以防止Safari浏览器页面打开Facebook登录,但会在应用中弹出一个屏幕本身。然后我为Facebook创建了一个帮助类,头文件代码在这里。
#import< UIKit / UIKit.h>
#importFBConnect.h
@interface FaceBookHelper:UIViewController
< FBRequestDelegate,
FBDialogDelegate,
FBSessionDelegate> {
Facebook * facebook;
NSArray *权限;
}
@property(只读)Facebook * facebook;
- (void)login;
- (void)getUserInfo:(id)sender;
- (void)getUserFriendList:(id)sender;
- (void)postToFriendsWall;
.m文件。
static NSString * kAppId = @xxx;
#define ACCESS_TOKEN_KEY @fb_access_token
#define EXPIRATION_DATE_KEY @fb_expiration_date
@implementation FaceBookHelper
@synthesize Facebook;
////////////////////////////////////// ////////////////////////////////////////////////// //////
// UIViewController
/ **
*初始化
* /
- (id)init {
if(self = [super init]){
facebook = [[Facebook alloc] initWithAppId:kAppId];
facebook.sessionDelegate = self;
permissions = [[NSArray arrayWithObjects:
@email,@read_stream,@user_birthday,
@user_about_me,@publish_stream,@offline_access,nil ]留]
[自我登录];
}
return self;
}
///////////////////////// ////////////////////////////////////////////////// //////////////////
// NSObject
- (void)dealloc {
[facebook release];
[权限释放];
[super dealloc];
}
////////////////////////////////////// ////////////////////////////////////////////////// ////////
//私人
/ **
*登录。
* /
- (void)login {
//仅当访问令牌无效时授权
//如果*是*有效,则不需要进行身份验证。只要移动
如果(![facebook isSessionValid]){
[facebook authorize:permissions delegate:self];
}
}
/ **
*这只是你在accessToken上获得保留的地方
*
* * /
- (void)fbDidLogin {
NSLog(@已登录);
NSLog(@访问令牌是%@,facebook.accessToken);
NSLog(@到期日为%@,facebook.expirationDate);
//将值存储在NSUserDefaults
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:facebook.accessToken forKey:ACCESS_TOKEN_KEY];
[defaults setObject:facebook.expirationDate forKey:EXPIRATION_DATE_KEY];
[默认同步];
//这是登录的最佳地点,因为这里我们知道用户已经登录了
[self getUserInfo:self];
// [self getUserFriendList:self];
// [self postToFriendsWall];
}
- (void)fbDidNotLogin:(BOOL)已取消{
NSLog(@无法登录);
}
- (void)getUserInfo:(id)sender {
[facebook requestWithGraphPath:@meandDelegate:self];
}
- (void)getUserFriendList:(id)sender {
[facebook requestWithGraphPath:@me / friendsandDelegate:self];
}
////////////////////////////////////// /////////////////////
// FBRequestDelegate
/ **
*当Facebook API请求返回响应时调用。这个回调
*可以让您访问原始响应。在
*(void)请求之前调用:(FBRequest *)请求didLoad:(id)result,
*传递解析的响应对象。
* /
- (void)request:(FBRequest *)request didReceiveResponse :( NSURLResponse *)response {
NSLog(@Inside didReceiveResponse:received response);
// NSLog(@状态码@,[response statusCode]);
NSLog(@URL @,[响应URL]);
}
/ **
*当请求返回并且其响应已解析为
*对象时调用。结果对象可以是字典,数组,字符串,
*或数字,具体取决于API响应的格式。如果您需要访问原始响应
*,请使用:
*
*(void)request:(FBRequest *)请求
* didReceiveResponse :( NSURLResponse *)响应
* /
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(@Inside didLoad);
if([result isKindOfClass:[NSArray class]]){
result = [result objectAtIndex:0];
}
//当我们要求用户信息时,会发生这种情况。
if([result isKindOfClass:[NSDictionary class]]){
// NSDictionary * hash = result;
NSLog(@Birthday:%@,[result objectForKey:@birthday]);
NSLog(@Name:%@,[result objectForKey:@name]);
}
if([result isKindOfClass:[NSData class]])
{
NSLog(@Profile Picture);
// [profilePicture release];
// profilePicture = [[UIImage alloc] initWithData:result];
}
NSLog(@请求返回%@,结果);
// if([result objectForKey:@owner]){}
};
/ **
*当错误阻止Facebook API请求成功完成
*时调用。
* /
- (void)request:(FBRequest *)请求didFailWithError:(NSError *)错误{
// [self.label setText:[error localizedDescription]];
};
//////////////////////////////////// ////////////////////////
// FBDialogDelegate
/ **
* UIServer对话框成功返回时调用。
* /
- (void)dialogDidComplete:(FBDialog *)dialog {
// [self.label setText:@publish successfully];
}
@end
I am using the Facebook iOS SDK for iPhone. I initialize the Facebook instance
facebook = [[Facebook alloc] initWithAppId:kAppId];
And then I do login:
[facebook authorize:permissions delegate:self];
After I logged in to Facebook I am doing the following to get the user profile information:
[facebook requestWithGraphPath:@"me" andDelegate:self];
NSMutableData *response = [fbRequest responseText];
unsigned char *firstBuffer = [response mutableBytes];
NSLog(@"Got Facebook Profile: : \"%s\"\n", (char *)firstBuffer);
But I get the following on my console:
Got Facebook Profile: "(null)"
What am I doing wrong, also I believe that Facebook response is a json string and I am looking to get a hold of that json string.
I thought may be I should make it a wiki and tell the people how I am doing it. because lot of people are facing similar problem.
The first thing that I did was.
In Facebook.m class I added the following statement in the following method
(void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth
safariAuth:(BOOL)trySafariAuth
trySafariAuth = NO;
This prevents a safari page to get open for the facebook login, but it pops up a screen in app itself. Then i created a helper class for Facebook, the header file code is here.
#import <UIKit/UIKit.h>
#import "FBConnect.h"
@interface FaceBookHelper : UIViewController
<FBRequestDelegate,
FBDialogDelegate,
FBSessionDelegate>{
Facebook *facebook;
NSArray *permissions;
}
@property(readonly) Facebook *facebook;
- (void)login;
-(void)getUserInfo:(id)sender;
- (void)getUserFriendList:(id)sender;
-(void)postToFriendsWall;
The .m file.
static NSString* kAppId = @"xxx";
#define ACCESS_TOKEN_KEY @"fb_access_token"
#define EXPIRATION_DATE_KEY @"fb_expiration_date"
@implementation FaceBookHelper
@synthesize facebook;
//////////////////////////////////////////////////////////////////////////////////////////////////
// UIViewController
/**
* initialization
*/
- (id)init {
if (self = [super init]) {
facebook = [[Facebook alloc] initWithAppId:kAppId];
facebook.sessionDelegate = self;
permissions = [[NSArray arrayWithObjects:
@"email", @"read_stream", @"user_birthday",
@"user_about_me", @"publish_stream", @"offline_access", nil] retain];
[self login];
}
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// NSObject
- (void)dealloc {
[facebook release];
[permissions release];
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// private
/**
* Login.
*/
- (void)login {
// only authorize if the access token isn't valid
// if it *is* valid, no need to authenticate. just move on
if (![facebook isSessionValid]) {
[facebook authorize:permissions delegate:self];
}
}
/**
* This is the place only where you will get the hold on the accessToken
*
**/
- (void)fbDidLogin {
NSLog(@"Did Log In");
NSLog(@"Access Token is %@", facebook.accessToken );
NSLog(@"Expiration Date is %@", facebook.expirationDate );
// Store the value in the NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:facebook.accessToken forKey:ACCESS_TOKEN_KEY];
[defaults setObject:facebook.expirationDate forKey:EXPIRATION_DATE_KEY];
[defaults synchronize];
// This is the best place to login because here we know that user has already logged in
[self getUserInfo:self];
//[self getUserFriendList:self];
//[self postToFriendsWall];
}
- (void)fbDidNotLogin:(BOOL)cancelled {
NSLog(@"Failed to log in");
}
- (void)getUserInfo:(id)sender {
[facebook requestWithGraphPath:@"me" andDelegate:self];
}
- (void)getUserFriendList:(id)sender {
[facebook requestWithGraphPath:@"me/friends" andDelegate:self];
}
////////////////////////////////////////////////////////////////////////////////
// FBRequestDelegate
/**
* 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(@"Inside didReceiveResponse: received response");
//NSLog(@"Status Code @", [response statusCode]);
NSLog(@"URL @", [response URL]);
}
/**
* 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(@"Inside didLoad");
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
// When we ask for user infor this will happen.
if ([result isKindOfClass:[NSDictionary class]]){
//NSDictionary *hash = result;
NSLog(@"Birthday: %@", [result objectForKey:@"birthday"]);
NSLog(@"Name: %@", [result objectForKey:@"name"]);
}
if ([result isKindOfClass:[NSData class]])
{
NSLog(@"Profile Picture");
//[profilePicture release];
//profilePicture = [[UIImage alloc] initWithData: result];
}
NSLog(@"request returns %@",result);
//if ([result objectForKey:@"owner"]) {}
};
/**
* Called when an error prevents the Facebook API request from completing
* successfully.
*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
//[self.label setText:[error localizedDescription]];
};
////////////////////////////////////////////////////////////////////////////////
// FBDialogDelegate
/**
* Called when a UIServer Dialog successfully return.
*/
- (void)dialogDidComplete:(FBDialog *)dialog {
//[self.label setText:@"publish successfully"];
}
@end
这篇关于如何使用Facebook iOS SDK检索Facebook响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!