Using Facebook Graph API on iOS

半城伤御伤魂 提交于 2019-12-01 08:28:56

The problem here is:

The facebook which is authororized is AppDelegate's facebook object, not your ViewController's facebook.

Solution:

Instead allocating new Facebook object for every ViewController or where you needed. you should make a property of your application delegate. like this:

in appDelegate.h

@property(nonatomic, retain) Facebook *facebook;

and synthesize it in appDelegate.m and now put initialization of Facebook in

- (BOOL)application:(UIApplication *)ap didFinishLaunchingWithOptions:(NSDictionary *)op
{
// other code.... 

    facebook = [[Facebook alloc] initWithAppId:@"XXXXXXXXXXX" andDelegate:self];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
        NSLog(@"AccessToken: %@ ExpirationDate: %@", facebook.accessToken, facebook.expirationDate);
    }else{
        NSLog(@"No AccessToken or ExpirationDate");
    }
    return true;
}

now where do you want to use it, write something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    //...
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];     
    facebook = app.facebook;    
    if (![facebook isSessionValid]) {
        [facebook authorize:[NSArray arrayWithObjects:@"publish_stream", nil]];
    }
}

Try to deauthorize your application and then authorize it again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!