Discord 上的 React-native 分享

问题描述 投票:0回答:2

我正在一个项目中实现一项功能,我们希望用户能够在不和谐上分享帖子。使用 https://react-native-community.github.io/react-native-share/docs/share-single

在 facebook 或 twitter 上实现共享很容易

但是 shareSingle 上不支持不和谐,并且我不希望有一个共享按钮调用可能链接到不和谐的本机共享菜单,我想要一个直接重定向到不和谐的不和谐图标。但我什至找不到一种方法来打开带有 url 模式或通用链接的不和谐应用程序来触发该应用程序(discord:// 或discord://discord 或discordapp:// ...)。

我试图找到一种方法来访问本机共享,以便单独打开不和谐共享,但找不到方法。

有人实现了不和谐共享,并且对如何在反应原生中实现这一目标有任何建议吗?

react-native discord share deep-linking
2个回答
2
投票

您可以创建一个项目并添加以下文件:

android/src/main/java/cl/json/social/DiscordShare.java

package cl.json.social;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import java.io.File;
import android.os.Environment;
import android.net.Uri;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableMap;


public class DiscordShare extends SingleShareIntent {

    private static final String PACKAGE = "com.discord";
    private static final String PLAY_STORE_LINK = "https://play.google.com/store/apps/details?id=com.discord";

    public DiscordShare(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public void open(ReadableMap options) throws ActivityNotFoundException {
        super.open(options);
        //  extra params here
        this.openIntentChooser();
    }

    @Override
    protected String getPackage() {
        return PACKAGE;
    }

    @Override
    protected String getDefaultWebLink() {
        return null;
    }

    @Override
    protected String getPlayStoreLink() {
        return PLAY_STORE_LINK;
    }
}

编辑android/src/main/java/cl/json/RNShareModule.java

package cl.json;
// ...

import cl.json.social.DiscordShare;
public class RNShareModule extends ReactContextBaseJavaModule implements ActivityEventListener {
 // ...
private enum SHARES {
        facebook,
        generic,
        pagesmanager,
        twitter,
        whatsapp,
        instagram,
        instagramstories,
        googleplus,
        email,
        pinterest,
        messenger,
        snapchat,
        sms,
        linkedin,
        discord; // ADDED


        public static ShareIntent getShareClass(String social, ReactApplicationContext reactContext) {
            SHARES share = valueOf(social);
            switch (share) {
                case generic:
                    return new GenericShare(reactContext);
                case facebook:
                    return new FacebookShare(reactContext);
                case pagesmanager:
                    return new FacebookPagesManagerShare(reactContext);
                case twitter:
                    return new TwitterShare(reactContext);
                case whatsapp:
                    return new WhatsAppShare(reactContext);
                case instagram:
                    return new InstagramShare(reactContext);
                case instagramstories:
                    return new InstagramStoriesShare(reactContext);
                case googleplus:
                    return new GooglePlusShare(reactContext);
                case email:
                    return new EmailShare(reactContext);
                case pinterest:
                    return new PinterestShare(reactContext);
                case sms:
                    return new SMSShare(reactContext);
                case snapchat:
                    return new SnapChatShare(reactContext);
                case messenger:
                    return new MessengerShare(reactContext);
                case linkedin:
                    return new LinkedinShare(reactContext);
                case discord:
                    return new DiscordShare(reactContext); // ADDED
                default:
                    return null;
            }
        }
    };

}
// ...

最后编辑index.js

//...
class RNShare {
//...
static Social = {
    FACEBOOK: NativeModules.RNShare.FACEBOOK || 'facebook',
    FACEBOOK_STORIES: NativeModules.RNShare.FACEBOOK_STORIES || 'facebook-stories',
    PAGESMANAGER: NativeModules.RNShare.PAGESMANAGER || 'pagesmanager',
    TWITTER: NativeModules.RNShare.TWITTER || 'twitter',
    WHATSAPP: NativeModules.RNShare.WHATSAPP || 'whatsapp',
    INSTAGRAM: NativeModules.RNShare.INSTAGRAM || 'instagram',
    INSTAGRAM_STORIES: NativeModules.RNShare.INSTAGRAM_STORIES || 'instagramstories',
    GOOGLEPLUS: NativeModules.RNShare.GOOGLEPLUS || 'googleplus',
    EMAIL: NativeModules.RNShare.EMAIL || 'email',
    PINTEREST: NativeModules.RNShare.PINTEREST || 'pinterest',
    LINKEDIN: NativeModules.RNShare.LINKEDIN || 'linkedin',
    SMS: NativeModules.RNShare.SMS || 'sms',
    DISCORD: NativeModules.RNShare.DISCORD || 'discord', // ADDED
  };
// ...
}

在您的项目中使用:

    Share.shareSingle({
      title: 'test',
      message: 'hola mundo',
      url: 'https://json.cl',
      social: Share.Social.DISCORD,
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        err && console.log(err);
      });

结果:


0
投票

您可以修改IOS代码如下: node_modules/react-native-share/ios/DiscordShare.m


#import "DiscordShare.h"
#import <AVFoundation/AVFoundation.h>
@import Photos;

@implementation DiscordShare
    RCT_EXPORT_MODULE();
- (void)shareSingle:(NSDictionary *)options
    failureCallback:(RCTResponseErrorBlock)failureCallback
    successCallback:(RCTResponseSenderBlock)successCallback {
    
    NSString *text = [RCTConvert NSString:options[@"message"]];
    text = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef) text, NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8));
    
    NSString *url = [RCTConvert NSString:options[@"url"]];
    
    NSString *discordMsg = [NSString stringWithFormat:@"discord://message?text=%@", text];
    NSString *discordMsgUrl = [NSString stringWithFormat:@"discord://message?text=%@&url%@", text, url];

    NSString * urlDiscord = url ? discordMsgUrl : discordMsg;
    
    NSURL * shareURL = [NSURL URLWithString:urlDiscord];
    
    
    if ([[UIApplication sharedApplication] canOpenURL: shareURL]) {
        [[UIApplication sharedApplication] openURL: shareURL];
        successCallback(@[@true, @""]);
    } else {
        // Cannot open discord
        NSString *stringURL = @"https://apps.apple.com/us/app/discord-chat-talk-hangout/id985746746";
        NSURL *url = [NSURL URLWithString:stringURL];
        
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
        
        NSString *errorMessage = @"Not installed";
        NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedString(errorMessage, nil)};
        NSError *error = [NSError errorWithDomain:@"com.rnshare" code:1 userInfo:userInfo];
        
        NSLog(@"%@", errorMessage);
        failureCallback(error);
    }
}

@end


node_modules/react-native-share/ios/DiscordShare.h

#import <UIKit/UIKit.h>
// import RCTConvert
#import <React/RCTConvert.h>
// import RCTBridge
#import <React/RCTBridge.h>
// import RCTUIManager
#import <React/RCTUIManager.h>
// import RCTLog
#import <React/RCTLog.h>
// import RCTUtils
#import <React/RCTUtils.h>
@interface DiscordShare : NSObject <RCTBridgeModule>

- (void) shareSingle:(NSDictionary *)options failureCallback:(RCTResponseErrorBlock)failureCallback successCallback:(RCTResponseSenderBlock)successCallback;

@end

node_modules/react-native-share/ios/RNShare.m

#import <MessageUI/MessageUI.h>
#import "RNShare.h"
// import RCTConvert
#import <React/RCTConvert.h>
// import RCTLog
#import <React/RCTLog.h>
// import RCTUtils
#import <React/RCTUtils.h>
// import RCTBridge
#import <React/RCTBridge.h>
// import RCTBridge
#import <React/RCTUIManager.h>
#import "GenericShare.h"
#import "WhatsAppShare.h"
#import "InstagramShare.h"
#import "DiscordShare.h"        // ADD LINE
#import "InstagramStories.h"
#import "FacebookStories.h"
#import "GooglePlusShare.h"
#import "EmailShare.h"
.....

@implementation RNShare

RCTResponseErrorBlock rejectBlock;
RCTResponseSenderBlock resolveBlock;

// we need this since this controller
// may implement a delegate and could be garbage collected
// before it is called
EmailShare *shareCtl;

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup
{
    return YES;
}

- (id) init
{
    if ((self = [super init])) {
        shareCtl = [[EmailShare alloc] init];
    }
    return self;
}

- (CGRect)sourceRectInView:(UIView *)sourceView
             anchorViewTag:(NSNumber *)anchorViewTag
{
    if (anchorViewTag) {
        UIView *anchorView = [self.bridge.uiManager viewForReactTag:anchorViewTag];
        return [anchorView convertRect:anchorView.bounds toView:sourceView];
    } else {
        return (CGRect){sourceView.center, {1, 1}};
    }
}

- (BOOL)isImageMimeType:(NSString *)data {
    NSRange range = [data rangeOfString:@"data:image" options:NSCaseInsensitiveSearch];
    if (data && range.location != NSNotFound) {
        return true;
    } else {
        return false;
    }
}

RCT_EXPORT_MODULE()

- (NSDictionary *)constantsToExport
{
  return @{
    @"FACEBOOK": @"facebook",
    @"FACEBOOKSTORIES": @"facebookstories",
    @"TWITTER": @"twitter",
    @"GOOGLEPLUS": @"googleplus",
    @"WHATSAPP": @"whatsapp",
    @"INSTAGRAM": @"instagram",
    @"INSTAGRAMSTORIES": @"instagramstories",
    @"TELEGRAM": @"telegram",
    @"EMAIL": @"email",
    @"MESSENGER": @"messanger",
    @"VIBER": @"viber",
    @"DISCORD": @"discord",    // ADD LINE

    @"SHARE_BACKGROUND_IMAGE": @"shareBackgroundImage",
    @"SHARE_BACKGROUND_VIDEO": @"shareBackgroundVideo",
    @"SHARE_STICKER_IMAGE": @"shareStickerImage",
    @"SHARE_BACKGROUND_AND_STICKER_IMAGE": @"shareBackgroundAndStickerImage",
  };
}

RCT_EXPORT_METHOD(shareSingle:(NSDictionary *)options
                  failureCallback:(RCTResponseErrorBlock)failureCallback
                  successCallback:(RCTResponseSenderBlock)successCallback)
{
    NSString *social = [RCTConvert NSString:options[@"social"]];
    if (social) {
        NSLog(@"%@", social);
        if([social isEqualToString:@"facebook"]) {
            NSLog(@"TRY OPEN FACEBOOK");
            GenericShare *shareCtl = [[GenericShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback serviceType: SLServiceTypeFacebook inAppBaseUrl:@"fb://"];
        } else if([social isEqualToString:@"facebookstories"]) {
            NSString *appId = [RCTConvert NSString:options[@"appId"]];
            if (appId) {
                NSLog(@"TRY OPEN FACEBOOK STORIES");
                FacebookStories *shareCtl = [[FacebookStories alloc] init];
                [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
            } else {
                RCTLogError(@"key 'appId' missing in options");
                return;
            }
        } else if([social isEqualToString:@"twitter"]) {
            NSLog(@"TRY OPEN Twitter");
            GenericShare *shareCtl = [[GenericShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback serviceType: SLServiceTypeTwitter inAppBaseUrl:@"twitter://"];
        } else if([social isEqualToString:@"googleplus"]) {
            NSLog(@"TRY OPEN google plus");
            GooglePlusShare *shareCtl = [[GooglePlusShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        } else if([social isEqualToString:@"whatsapp"]) {
            NSLog(@"TRY OPEN whatsapp");
            WhatsAppShare *shareCtl = [[WhatsAppShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        } else if([social isEqualToString:@"instagram"]) {
            NSLog(@"TRY OPEN instagram");
            InstagramShare *shareCtl = [[InstagramShare alloc] init];
            if([self isImageMimeType:options[@"url"]]) {// Condition to handle image
                [shareCtl shareSingleImage:options failureCallback: failureCallback successCallback: successCallback];
            } else {
                [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
            }
        } else if([social isEqualToString:@"instagramstories"]) {
            NSLog(@"TRY OPEN instagram-stories");
            InstagramStories *shareCtl = [[InstagramStories alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
         } else if([social isEqualToString:@"telegram"]) {
            NSLog(@"TRY OPEN telegram");
            TelegramShare *shareCtl = [[TelegramShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        } else if([social isEqualToString:@"email"]) {
            NSLog(@"TRY OPEN email");
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        } else if([social isEqualToString:@"viber"]) {
            NSLog(@"TRY OPEN viber");
            ViberShare *shareCtl = [[ViberShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        } else if([social isEqualToString:@"discord"]) {
            NSLog(@"TRY OPEN discord");
            // ADD NEXT LINE
            DiscordShare *shareCtl = [[DiscordShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        } else if([social isEqualToString:@"messenger"]) {
            NSLog(@"TRY OPEN messenger");
            MessengerShare *shareCtl = [[MessengerShare alloc] init];
            [shareCtl shareSingle:options failureCallback: failureCallback successCallback: successCallback];
        }
    } else {
        RCTLogError(@"key 'social' missing in options");
        return;
    }
}

RCT_EXPORT_METHOD(open:(NSDictionary *)options
                  failureCallback:(RCTResponseErrorBlock)failureCallback
                  successCallback:(RCTResponseSenderBlock)successCallback)
{
    if (RCTRunningInAppExtension()) {
        RCTLogError(@"Unable to show action sheet from app extension");
        return;
    }

    NSMutableArray<id> *items = [NSMutableArray array];
    NSString *message = [RCTConvert NSString:options[@"message"]];
    if (message) {
        [items addObject:message];
    }
    BOOL saveToFiles = [RCTConvert BOOL:options[@"saveToFiles"]];
    NSArray *urlsArray = options[@"urls"];
    for (int i=0; i<urlsArray.count; i++) {
        NSURL *URL = [RCTConvert NSURL:urlsArray[i]];
        if (URL) {
            if ([URL.scheme.lowercaseString isEqualToString:@"data"]) {
                NSError *error;
                NSData *data = [NSData dataWithContentsOfURL:URL
                                                     options:(NSDataReadingOptions)0
                                                       error:&error];
                if (!data) {
                    failureCallback(error);
                    return;
                }
                if (saveToFiles) {
                    NSURL *filePath = [RNShareUtils getPathFromBase64:URL.absoluteString with:data];
                    if (filePath) {
                        [items addObject: filePath];
                    }
                } else {
                    [items addObject:data];
                }
            } else {
                [items addObject:URL];
            }
        }
    }

    NSArray *activityItemSources = options[@"activityItemSources"];
    if (activityItemSources) {
        [activityItemSources enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            RNShareActivityItemSource *activityItemSource = [[RNShareActivityItemSource alloc] initWithOptions:obj];
            [items addObject:activityItemSource];
        }];
    }

    if (items.count == 0) {
        RCTLogError(@"No `url` or `message` to share");
        return;
    }

    UIViewController *controller = RCTPresentedViewController();

    if (saveToFiles) {
        NSArray *urls = [items filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
            return [evaluatedObject isKindOfClass:[NSURL class]];
        }]];

        if (urls.count == 0) {
            RCTLogError(@"No `urls` to save in Files");
            return;
        }
        if (@available(iOS 11.0, macCatalyst 13.1, *)) {
            resolveBlock = successCallback;
            rejectBlock = failureCallback;
            UIDocumentPickerViewController *documentPicker = nil;
            if (@available(iOS 15.0, macCatalyst 15.0, *)) {
                documentPicker = [[UIDocumentPickerViewController alloc] initForExportingURLs:urls asCopy:YES];
            } else {
                documentPicker = [[UIDocumentPickerViewController alloc] initWithURLs:urls inMode:UIDocumentPickerModeExportToService];
            }
            [documentPicker setDelegate:self];
            [controller presentViewController:documentPicker animated:YES completion:nil];
            return;
        }
    }

    UIActivityViewController *shareController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];

    NSString *subject = [RCTConvert NSString:options[@"subject"]];
    if (subject) {
        [shareController setValue:subject forKey:@"subject"];
    }

    NSArray *excludedActivityTypes = [RCTConvert NSStringArray:options[@"excludedActivityTypes"]];
    if (excludedActivityTypes) {
        shareController.excludedActivityTypes = excludedActivityTypes;
    }

    __weak UIActivityViewController* weakShareController = shareController;
    shareController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, __unused NSArray *returnedItems, NSError *activityError) {
        
        // always dismiss since this may be called from cancelled shares
        // but the share menu would remain open, and our callback would fire again on close
        if(weakShareController){
            // closing activity view controller
            [weakShareController dismissViewControllerAnimated:true completion:nil];
        } else {
            [controller dismissViewControllerAnimated:true completion:nil];
        }

        
        if (activityError) {
            failureCallback(activityError);
        } else {
            successCallback(@[@(completed), RCTNullIfNil(activityType)]);
        }
        
        // clear the completion handler to prevent cycles
        if(weakShareController){
            weakShareController.completionWithItemsHandler = nil;
        }
    };

    shareController.modalPresentationStyle = UIModalPresentationPopover;
    NSNumber *anchorViewTag = [RCTConvert NSNumber:options[@"anchor"]];
    if (!anchorViewTag) {
        shareController.popoverPresentationController.permittedArrowDirections = 0;
    }
    shareController.popoverPresentationController.sourceView = controller.view;
    shareController.popoverPresentationController.sourceRect = [self sourceRectInView:controller.view anchorViewTag:anchorViewTag];

    [controller presentViewController:shareController animated:YES completion:nil];

    shareController.view.tintColor = [RCTConvert UIColor:options[@"tintColor"]];
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    if (rejectBlock) {
        NSError *error = [NSError errorWithDomain:@"CANCELLED" code: 500 userInfo:@{NSLocalizedDescriptionKey:@"PICKER_WAS_CANCELLED"}];
        rejectBlock(error);
    }
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    if (resolveBlock) {
        resolveBlock(@[@(YES), @"com.apple.DocumentsApp"]);
    }
}

@end


node_modules/react-native-share/src/index.tsx

.....
const RNShare = {
     .......
     MESSENGER: NativeModules.RNShare.MESSENGER || Social.Messenger,
     SNAPCHAT: NativeModules.RNShare.SNAPCHAT || Social.Snapchat,
     VIBER: NativeModules.RNShare.VIBER || Social.Viber,
     DISCORD: NativeModules.RNShare.DISCORD || 'discord', // ADDED
   },
.....

© www.soinside.com 2019 - 2024. All rights reserved.