获取用户头像并不需要额外的权限,但是排行榜需要用到publish_actions权限,所以在使用之前需要先获取该权限。并且这个权限不能在登录的时候跟那些只读权限一起获取,需要单独获取。
1、判断当前是否具有publish_actions权限
if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"publish_actions"])
{
return true;
}else
{
return false;
}
2、申请publish_actions权限
AppController * pController=[AppController getSharedInstance];
FBSDKLoginManager * manager=[[FBSDKLoginManager alloc] init];
NSArray *permissions = [[NSArray alloc] initWithObjects: @"publish_actions", nil];
[manager logInWithPublishPermissions:permissions fromViewController:pController.viewController handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
//do something;
}else
{
//do something;
}
}];
3、上传用户分数
NSString *score = [NSString stringWithFormat:@"%d", 12345];//12345替换成要上传的分数
NSDictionary *params = @{@"score": score};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"/me/scores"
parameters:params
HTTPMethod:@"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Handle the result
if(!error && result)
{
NSLog(@"result:%@",result);
return;
}else{
NSLog(@"error:%@", error);
}
}];
4、获取用户分数
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:@"%@/scores", [FBSDKSettings appID]]
parameters:@{@"fields":@"score,user"}
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Handle the result
if(!error && result){
NSLog(@"result:%@",result);
NSArray* fetchedScoreData = [[NSArray alloc] initWithArray:[result objectForKey:@"data"]];
if ([fetchedScoreData count] > 0){
// do something
}
}else{
NSLog(@"error:%@", error);
}
}];
5、获取用户头像
这里将获取的头像保存到文件里面,需要注意的一点是writeToFile操作完成的时候,如果立即用该图像生成一个Sprite会出现头像是一个黑色方块的情况。可以通过在一小段延迟之后,再使用该图像来避免黑块的情况。
string strId="xxxxxxxxxxx";//用户id
int width=200; //实际宽高可以根据需求修改
int height=200;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%s/picture?width=%d&height=%d", strId.c_str(), width ,height]];
dispatch_queue_t downloader = dispatch_queue_create("PicDownloader", NULL);
dispatch_async(downloader, ^
{
string strSavePath=FileUtils::getInstance()->getWritablePath();
strSavePath+="FBImage";
strSavePath+=strId+".png";
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
NSString * sPic = [NSString stringWithFormat:@"%s",strSavePath.c_str()];
if([UIImagePNGRepresentation(image) writeToFile:sPic atomically:YES])
{
//do something;
}
});