简体   繁体   中英

Override UIActivityViewController to switch out to Facebook app (for Open Graph stories)

There's two kinds of Facebook story: standard 'link' content, or richer Open Graph stories.

iOS provides UIActivityController , which lets you share 'link' content but doesn't let you perform Open Graph sharing. For that I use FBSDKShareKit , which accomplishes this by switching out to the Facebook app if it's installed).

I want best of both worlds, though: present a UIActivityController , and whenever Facebook is selected (see image), I want it to switch out to the Facebook app. Is this possible?

Facebook按钮

It is possible :) Just create a new class - lets say FacebookActivityItem:

// .h
@protocol FacebookActivityItemDelegate <NSObject>
- (void)facebookItemWasSelected;
@end

@interface FacebookActivityItem : NSObject<UIActivityItemSource>
@property (nonatomic, weak) id <FacebookActivityItemDelegate> delegate;
@end

// .m
@implementation FacebookActivityItem

/// called to determine data type. only the class of the return type is consulted. it should match what -itemForActivityType: returns later
- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController {
    return UIActivityTypePostToFacebook;
}

/// called to fetch data after an activity is selected. you can return nil.
- (nullable id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {

    if ([activityType isEqualToString:UIActivityTypePostToFacebook]) {

        if (self.delegate != nil) {
            [self.delegate facebookItemWasSelected];
        }
    }

    return nil;
}

@end

Now in your UIViewController, add an instance of this to the UIActivityViewController:

FacebookActivityItem *fbActivityItem = [FacebookActivityItem new];
fbActivityItem.delegate = self;

self.activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[fbActivityItem] applicationActivities:nil];

Now implement the method -facebookItemWasSelected in your UIViewController and tell it that it implements the FacebookActivityItemDelegate. In this method just dismiss the activityViewController and implement your custom form with the FacebookSDK!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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