如何将自定义 activity 添加到 SFSafariViewController?

How to add a custom activity to SFSafariViewController?

我想将自定义 activity (UIActivity) 添加到我在我的应用程序中显示的 SFSafariViewController。我该怎么做?

1。创建 UIActivity.

的子类

实施所有 required methods of the class, and when initializing the activity, pass in the URL of the page at that point and initialize your UIViewController, as prepareWithActivityItems: isn't called within the SFSafariViewController context (rdar://24138390)。如果您的 activity 不显示 UI,而是在初始化期间保存 URL,以便您可以在用户点击操作时处理它。

完整示例:

@interface YourActivity : UIActivity {
    UIViewController *activityViewController;
}
- (id)initWithURL:(NSURL *)url;
@end


@implementation YourActivity

- (id)initWithURL:(NSURL *)url
{
    self = [super init];
    if (self)
    {
        [self prepareWithURL:url];
    }
    return self;
}

- (NSString *)activityType
{
    return @"YourTypeName";
}

- (NSString *)activityTitle
{
    return @"Perform Action";
}

- (UIImage *)activityImage
{
    return [UIImage imageNamed:@"YourActionIcon"];
}

- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
{
    return YES;
}

- (void)prepareWithActivityItems:(NSArray *)activityItems
{
    NSURL* url = nil;
    for (NSObject* obj in activityItems)
    {
        if ([obj isKindOfClass:[NSURL class]])
        {
            url = (NSURL*)obj;
        }
    }
    
    [self prepareWithURL:url];
}

- (void) prepareWithURL:(NSURL*)url
{
    // initialize your UI using the given URL
    activityViewController = ... // initialize your UI here
}

- (UIViewController *)activityViewController
{
    return activityViewController;
}

+ (UIActivityCategory)activityCategory
{
    return UIActivityCategoryShare;
}


@end

2。将 UIActivity 添加到 SFSafariViewController

在您的 SFSafariViewControllerDelegate 中执行以下方法,它会初始化 activity 并传入用户正在查看的页面的 URL。

- (NSArray<UIActivity *> *)safariViewController:(SFSafariViewController *)controller
                            activityItemsForURL:(NSURL *)URL
                                          title:(NSString *)title
{
    YourActivity* activity = [[YourActivity alloc] initWithURL:URL];
    return @[activity];
}