2011-03-02 56 views
9

我正在使用適用於iPhone的Facebook iOS SDK。我初始化Facebook的實例如何使用Facebook iOS SDK檢索Facebook響應

facebook = [[Facebook alloc] initWithAppId:kAppId]; 

然後我就登錄:

[facebook authorize:permissions delegate:self]; 

我登錄到Facebook後,我做以下,以獲取用戶配置文件信息:

[facebook requestWithGraphPath:@"me" andDelegate:self]; 
NSMutableData *response = [fbRequest responseText]; 
unsigned char *firstBuffer = [response mutableBytes]; 
NSLog(@"Got Facebook Profile: : \"%s\"\n", (char *)firstBuffer); 

但我在控制檯上得到以下內容:

Got Facebook Profile: "(null)" 

我在做什麼錯誤,我也相信Facebook的響應是一個JSON字符串,我期待得到該JSON字符串的保留。

+0

*旁註*:上面的代碼不再有效爲Facebook的iOS SDK 3.X – Raptor 2013-06-27 04:15:01

回答

25

我認爲可能是我應該讓它成爲一個維基,並告訴人們我是如何做到這一點的。因爲很多人都面臨類似的問題。

我做的第一件事是。

在Facebook.m類添加以下語句如下方法

(void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth 
          safariAuth:(BOOL)trySafariAuth 
trySafariAuth = NO; 

這可以防止的Safari網頁拿開的Facebook登錄,但它在應用程序本身會彈出一個屏幕。然後我爲Facebook創建了一個輔助類,頭文件代碼在這裏。

#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; 

該.m文件。

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 
+0

注:Facebook的iOS版SDK開闢了在Safari的認證頁面,因此用戶不需要登錄,如果他們已經通過Safari登錄。 iOS上的瀏覽器Cookie對於每個UIWebView都是分開的。因此,儘管上面的應用內方法更簡潔,但需要用戶進行更多的工作! iOS5可能會使這更容易,但它現在只支持Twitter(這很多是公共知識,而不是NDA)。 – pchap10k 2011-06-09 11:54:20

+0

getUserInfo怎麼樣? – BenB 2011-06-22 03:31:53

+0

我已通過添加該方法更新了我的回覆。 – Yogesh 2011-06-22 14:15:20

2

感謝這個提示Yogesh!

facebook.m您還可以設置在授權方法safariAuth PARAM。

- (void)authorize:(NSArray *)permissions 
    delegate:(id<FBSessionDelegate>)delegate { 

    ... 

    [self authorizeWithFBAppAuth:YES safariAuth:NO]; 
} 
+0

酷感謝馬丁 – Yogesh 2011-03-14 05:00:36

+0

我很想這樣做。 3.1是一場災難。 – 2012-12-18 22:35:45