zoukankan      html  css  js  c++  java
  • unity iOS分享视频到Facebook、Tik Tok

    Facebook提供的unity插件,关于分享部分的功能,只提供了分享好友和ShareApplinks,并没有提供其他的分享,比如分享视频。
    正好最近的项目有分享视频到facebook和分享到Tik Tok的功能,1.检测相关权限,2.复制相关视频到相册目录3.分享视频到对应平台。
    相关代码如下,贴出来与大家共享,可参考实现自己的功能。

    1. 引入头文件
    #import <AssetsLibrary/AssetsLibrary.h>
    #import "FBSDKShareVideo.h"
    #import "FBSDKShareVideoContent.h"
    #import "FBSDKShareDialog.h"
    #import "FBSDKHashtag.h"
    #import <TikTokOpenSDK/TikTokOpenSDKShare.h>
    
    1. 回调unity方法
    /// 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]);
    }
    
    1. 申请相册权限
    -(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"];
                   });
         
               }];
           }
    }
    
    1. 保存视频到相册目录(videoPath由unity提供)
    - (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(@"未能保存视频到相册");
            }
        }];
    }
    
    1. 获取相册视频(可根据自己需求,获取对应的视频文件)
    /// 获取相册中最后一个视频
    /// - 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;
    }
    
    1. facebook分享
    - (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);
    }
    
    1. facebook分享回调
    - (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults :(NSDictionary*)results {
        NSLog(@"FB: SHARE RESULTS=%@
    ",[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=%@
    ",[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=%@
    ",[sharer debugDescription]);
        [self SendMessage:@"ShareVideoResult" message:@"0|0|cancel"];
    }
    
    1. Tik Tok分享
    - (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];
            }
        }];
    }
    
  • 相关阅读:
    Docker之Harbor
    idea 代码块编辑(批量列编辑)快捷键 -- idea version 2018 不常用
    mysql 去除表中重复的数据,保留id最小的数据信息
    打家劫舍(动态规划+滚动数组+取模运算优化)
    利用线程异步调用
    idea 2019激活码
    mysql导出PDM表结构并带有注释
    安装GO
    GO语言
    项目启动
  • 原文地址:https://www.cnblogs.com/Yellow0-0River/p/15180042.html
Copyright © 2011-2022 走看看