Facebook提供的unity插件,关于分享部分的功能,只提供了分享好友和ShareApplinks,并没有提供其他的分享,比如分享视频。
正好最近的项目有分享视频到facebook和分享到Tik Tok的功能,1.检测相关权限,2.复制相关视频到相册目录3.分享视频到对应平台。
相关代码如下,贴出来与大家共享,可参考实现自己的功能。
#import <AssetsLibrary/AssetsLibrary.h>
#import "FBSDKShareVideo.h"
#import "FBSDKShareVideoContent.h"
#import "FBSDKShareDialog.h"
#import "FBSDKHashtag.h"
#import <TikTokOpenSDK/TikTokOpenSDKShare.h>
/// unity回调
/// @param methodName unity方法名
/// @param message 参数字符串
- (void)SendMessage:(NSString*)methodName message:(NSString*)message
{
NSLog(@"message->%@",message);
NSLog(@"methodName->%@", methodName);
UnitySendMessage("GameLaunch", [methodName UTF8String], [message UTF8String]);
}
-(void)GetAlbumPermissions:(NSString*)title message:(NSString*)message confirm:(NSString*)confirm cancel:(NSString*)cancel{
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized) {
[self SendMessage:@"IosAlbumPermission" message:@"1"];
return;
}
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
[self SendMessage:@"IosAlbumPermission" message:@"0"];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:confirm style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
UIViewController *viewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
if (viewController.presentedViewController && !viewController.presentedViewController.isBeingDismissed ) {
viewController = viewController.presentedViewController;
}
NSLayoutConstraint *constraint = [NSLayoutConstraint
constraintWithItem:alertController.view
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationLessThanOrEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:viewController.view.frame.size.height*2.0f];
[alertController.view addConstraint:constraint];
[viewController presentViewController:alertController animated:YES completion:^{}];
});
return ;
}
if (status == PHAuthorizationStatusNotDetermined) {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
// 回调是在子线程的
NSLog(@"%@",[NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{
if (status != PHAuthorizationStatusAuthorized) {
NSLog(@"未开启相册权限,请到设置中开启");
[self SendMessage:@"IosAlbumPermission" message:@"0"];
return ;
}
[self SendMessage:@"IosAlbumPermission" message:@"1"];
});
}];
}
}
- (void) SaveVideoToPhotoAlbum:(NSString*) videoPath {
PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
[photoLibrary performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:videoPath]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) {
NSLog(@"已保存视频到相册");
} else {
NSLog(@"未能保存视频到相册");
}
}];
}
/// 获取相册中最后一个视频
/// - Returns: 视频信息
- (PHAsset*) getLastVideo{
PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
// 相机胶卷相簿存储到数组
PHFetchResult<PHAsset *> *albumAssets = [PHAsset fetchAssetsInAssetCollection:cameraRoll options:nil];
PHAsset *videoAsset;
for(PHAsset *asset in albumAssets){
int fileType = (int)asset.mediaType;
if(fileType == PHAssetMediaTypeVideo)
{
videoAsset = asset;
}
}
return videoAsset;
}
- (void) FBShareVideo:(NSString*) shareTag
{
PHAsset *videoAsset = [self getLastVideo];
NSArray *array = [videoAsset.localIdentifier componentsSeparatedByString:@"/"];
NSString* assetStr = [NSString stringWithFormat:@"assets-library://asset/asset.mp4?id=%@&ext=mp4",[array objectAtIndex:0]];
NSURL* assetURL = [NSURL URLWithString:assetStr];
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
if (@available(iOS 11, *)) {
video.videoAsset = videoAsset;
}else{
video.videoURL = assetURL;
}
//调用fb的弹窗分享
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
FBSDKHashtag* hashTag = [FBSDKHashtag hashtagWithString:shareTag];
content.hashtag = hashTag;
FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];
dialog.shareContent = content;
dialog.fromViewController = UnityGetGLViewController();
dialog.delegate = self;
dialog.mode = FBSDKShareDialogModeNative;
BOOL state = [dialog show];
NSLog(@"assetURL is %@", assetURL);
NSLog(@"FBSDKShareDialog state %i", state);
}
- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults :(NSDictionary*)results {
NSLog(@"FB: SHARE RESULTS=%@\n",[results debugDescription]);
bool complete = [results objectForKey:@"didComplete"];
if(complete){
[self SendMessage:@"ShareVideoResult" message:@"0|1|null"];
}
}
- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
NSLog(@"FB: ERROR=%@\n",[error debugDescription]);
NSString* msg = [NSString stringWithFormat:@"0|0|error:%@",[error debugDescription]];
[self SendMessage:@"ShareVideoResult" message:msg];
}
- (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
NSLog(@"FB: CANCELED SHARER=%@\n",[sharer debugDescription]);
[self SendMessage:@"ShareVideoResult" message:@"0|0|cancel"];
}
- (void) TikTokShareVideo
{
PHAsset *videoAsset = [self getLastVideo];
NSMutableArray<NSString *> *mediaLocalIdentifiers = [NSMutableArray array];
[mediaLocalIdentifiers addObject:videoAsset.localIdentifier];
TikTokOpenSDKShareRequest *req = [[TikTokOpenSDKShareRequest alloc] init];
req.mediaType = TikTokOpenSDKShareMediaTypeVideo;
req.localIdentifiers = [mediaLocalIdentifiers copy];
req.landedPageType = TikTokOpenSDKLandedPageClip;
[req sendShareRequestWithCompletionBlock:^(TikTokOpenSDKShareResponse * _Nonnull Response) {
if(Response.errCode==0){
NSLog(@"分享成功");
[self SendMessage:@"ShareVideoResult" message:@"1|1|null"];
}else{
NSLog(@"分享失败,错误码:%li",Response.errCode);
NSLog(@"分享失败,shareState:%li",Response.shareState);
NSString* msgTemp = [NSString stringWithFormat:@"1|0|errorCode:%li,shareState:%li",Response.errCode,Response.shareState];
[self SendMessage:@"ShareVideoResult" message:msgTemp];
}
}];
}
原文:https://www.cnblogs.com/Yellow0-0River/p/15180042.html