繁体   English   中英

在iOS上使用Facebook Graph API

[英]Using Facebook Graph API on iOS

这是我在StackOverflow上的第一篇文章,但我用了很长时间......

我的问题基本上很简单,我想在用户的墙上分享UITextView(mShareText)的内容而不提示任何Dialog。 基本上,用户必须在UITextView上填写其消息,然后单击“ post ”UIButton。 简单不是吗?

我已下载Facebook iOS SDK并将其复制到我的项目中。 我在控制器的头文件中包含了“ FBConnect.h ”和“ Facebook.h ”并创建了一个var: Facebook* facebook ;控制器还实现了以下代理:FBSessionDelegate,FBRequestDelegate。

在我的控制器的实现文件中,当用户点击“post”UIButton时,我触发了IBAction。

- (IBAction)onShareByFBPressed:(id)sender {
NSLog(@"onShareByFBPressed");

// Facebook settings
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithCapacity:3];

[params setObject:mShareText.text forKey:@"message"];
[params setObject:@"http://www.example.com" forKey:@"link"];
[params setObject:@"https://www.example.com/myImg.jpg" forKey:@"picture"];

[facebook requestWithGraphPath:@"me/feed" 
                         andParams:params
                     andHttpMethod:@"POST"
                       andDelegate:self];
    [params release];
}

我在我的viewdidload上实现了这个:

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad");
    [super viewDidLoad];

(...)

    // Test facebook
    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");
    }
    if (![facebook isSessionValid]) {
        [facebook authorize:[NSArray arrayWithObjects:@"publish_stream", nil]];
    }
}

以下是由于代表我必须实现的不同方法:

// Pre 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [facebook handleOpenURL:url]; 
}

// For 4.2+ support
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url]; 
}

- (void)fbDidLogin {
    NSLog(@"fbDidLogin");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
}

- (void)fbSessionInvalidated{
    NSLog(@"fbSessionInvalidated");
}

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

- (void)fbDidExtendToken:(NSString*)accessToken expiresAt:(NSDate*)expiresAt{
    NSLog(@"fbDidExtendToken");
}

- (void)fbDidNotLogin:(BOOL)cancelled{
    NSLog(@"fbDidNotLogin");
}

- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"didReceiveResponse: %@", response);
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"didFailWithError: %@", [error description]);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Share on Facebook" 
                                                message:@"An error occured" 
                                               delegate:nil 
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
    [alert show];
    [alert release];
}

不幸的是,每当我尝试触发我的“onShareByFBPressed”方法时,我在日志中收到以下错误:

2012-02-17 13:02:06.401 Mixtapes[935:707] didFailWithError: Error Domain=facebookErrDomain     Code=10000 "The operation couldn’t be completed. (facebookErrDomain error 10000.)"     UserInfo=0x1f6f60 {error=<CFBasicHash 0x1f6660 [0x3ec6d630]>{type = mutable dict, count = 3,
entries =>
    2 : <CFString 0x1f64a0 [0x3ec6d630]>{contents = "type"} = <CFString 0x1f6b10     [0x3ec6d630]>{contents = "OAuthException"}
    3 : <CFString 0x1f6ab0 [0x3ec6d630]>{contents = "message"} = <CFString 0x1f6a10     [0x3ec6d630]>{contents = "An active access token must be used to query information about the     current user."}
    6 : <CFString 0x1f6e60 [0x3ec6d630]>{contents = "code"} = 2500
}
}

谁能告诉我我的实施有什么问题?

非常感谢。

最好的祝福。

编辑:@Adil

谢谢你的提议。 它实际上工作了一些时间。

有时我得到以下错误:

didFailWithError: Error Domain=facebookErrDomain Code=10000 "The operation couldn’t be     completed. (facebookErrDomain error 10000.)" UserInfo=0xa17e0d0 {error=<CFBasicHash 0xa171e10     [0x3ec6d630]>{type = mutable dict, count = 3,
entries =>
    2 : <CFString 0xa179d10 [0x3ec6d630]>{contents = "type"} = <CFString 0xa17a280     [0x3ec6d630]>{contents = "OAuthException"}
    3 : <CFString 0x6127710 [0x3ec6d630]>{contents = "message"} = <CFString 0xa178db0     [0x3ec6d630]>{contents = "Error validating access token: Session is invalid. This could be     because the application was uninstalled after the session was created."}
    6 : <CFString 0xa17e020 [0x3ec6d630]>{contents = "code"} = 190
}
}

谢谢你的帮助

这里的问题是:

被授权的facebook是AppDelegate的facebook对象,而不是ViewController的facebook。

解:

而是为每个ViewController或您需要的地方分配新的Facebook对象。 您应该创建应用程序delegate的属性。 像这样:

在appDelegate.h中

@property(nonatomic, retain) Facebook *facebook;

并在appDelegate.m中合成它,现在将Facebook初始化

- (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;
}

现在你想在哪里使用它,写下这样的东西:

- (void)viewDidLoad
{
    [super viewDidLoad];

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

尝试取消对您的应用程序的授权,然后再次授权

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM