美文网首页
iOS集成微信分享

iOS集成微信分享

作者: 最强的小强 | 来源:发表于2020-03-15 18:06 被阅读0次
    一、微信分享,首先利用CocoaPods,导入支付宝SDK
    pod 'WechatOpenSDK'
    
    二、 创建微信分享管理类 WechatShareManager
    // WechatShareManager.h
    #import <Foundation/Foundation.h>
    #import <WXApi.h>
    
    // 分享类型枚举
    typedef NS_ENUM(NSInteger, WechatShareType) {
        WechatShareTypeFriends,  // 好友
        WechatShareTypeTimeline,  // 朋友圈
    };
    
    // 分享后返回码枚举
    typedef NS_ENUM(int, WechatShareStatusCode){
        WechatShareSuccess     = 0, // 分享成功
        WechatShareCancleShare = 1,// 取消分享
        WechatShareFailed      = 2   // 分享失败
    };
    
    @interface WechatShareManager : NSObject
    
    // WechatShareManager是微信分享管理类
    
    
    + (id)shareInstance;
    
    + (BOOL)handleOpenUrl:(NSURL *)url;
    
    + (void)hangleWechatShareWith:(SendMessageToWXReq *)req;
    
    @end
    
    // WechatShareManager.m
    #import "WechatShareManager.h"
    #import <WXApi.h>
    
    @interface WechatShareManager()<WXApiDelegate>
    
    @end
    
    @implementation WechatShareManager
    
    + (id)shareInstance {
        static WechatShareManager *weChatShareInstance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            weChatShareInstance = [[WechatShareManager alloc] init];
        });
        return weChatShareInstance;
    }
    
    + (BOOL)handleOpenUrl:(NSURL *)url {
        return [WXApi handleOpenURL:url delegate:[WechatShareManager shareInstance]];
    }
    
    + (void)hangleWechatShareWith:(SendMessageToWXReq *)req {
        
    
        [WXApi sendReq:req completion:^(BOOL success) {
            //
        }];
    }
    
    #pragma mark - 微信分享回调
    
    - (void)onResp:(BaseResp *)resp {
        if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
            /*
             enum  WXErrCode {
             WXSuccess           = 0,    < 成功
             WXErrCodeCommon     = -1,  < 普通错误类型
             WXErrCodeUserCancel = -2,   < 用户点击取消并返回
             WXErrCodeSentFail   = -3,   < 发送失败
             WXErrCodeAuthDeny   = -4,   < 授权失败
             WXErrCodeUnsupport  = -5,   < 微信不支持
             };
             */
            SendMessageToWXResp *response = (SendMessageToWXResp *)resp;
            switch (response.errCode) {
                case WXSuccess: {
                    NSLog(@"微信分享成功");
                    [[NSNotificationCenter defaultCenter] postNotificationName:UserNotificationWechatShareSuccess
                                                                        object:nil
                                                                      userInfo:nil];
                    break;
                }
                case WXErrCodeCommon: {
                    NSLog(@"微信分享异常");
                    break;
                }
                case WXErrCodeUserCancel: {
                    NSLog(@"微信分享取消");
                    break;
                }
                case WXErrCodeSentFail: {
                    NSLog(@"微信分享失败");
                    [[NSNotificationCenter defaultCenter] postNotificationName:UserNotificationWechatShareFail
                                                                        object:nil
                                                                      userInfo:nil];
                    break;
                }
                case WXErrCodeAuthDeny: {
                    NSLog(@"微信分享授权失败");
                    break;
                }
                case WXErrCodeUnsupport: {
                    NSLog(@"微信分享版本暂不支持");
                    break;
                }
                default: {
                    break;
                }
            }
        }
    }
    
    
    三、微信分享的逻辑处理
    case ShareButtonTypeWechat:{
                // 分享到微信
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = self.shareTitle;
                message.description = self.shareDetails == nil ? @"":self.shareDetails;
                [message setThumbImage:self.shareCoverImageView];
                if (self.shareImage != nil) {
                    WXImageObject *imageObject = [WXImageObject object];
                    imageObject.imageData = self.shareImage;
                    message.mediaObject = imageObject;
                } else {
                    WXWebpageObject *webpageObject = [WXWebpageObject object];
                    webpageObject.webpageUrl = self.shareURL;
                    message.mediaObject = webpageObject;
                }
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = NO;
                req.message = message;
                req.scene = WXSceneSession;
                [WechatShareManager hangleWechatShareWith:req];
                break;
            }
    
    四、微信分享调用
    - (void)addNotionAction {
       [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(wechatShareSuccessAction)
                                                    name:UserNotificationWechatShareSuccess
                                                  object:nil];
       [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(wechatShareFailAction)
                                                    name:UserNotificationWechatShareFail
                                                  object:nil];
    }
    - (void)shareButtonClick {
       ShareView *shareView = [[ShareView alloc] initWithFrame:[UIScreen mainScreen].bounds];
       shareView.superViewController = self;
       shareView.shareTitle = @"大家哈";
       shareView.shareDetails = @"000000000000";
       shareView.shareCoverImageView = KImage(@"mine_people_boy");
       shareView.shareURL = @"https://www.baidu.com";
       shareView.shareImage = UIImagePNGRepresentation(KImage(@"mine_people_girl"));
       [self.view addSubview:shareView];
       [shareView showShareViewAction];
    }
    - (void)wechatShareSuccessAction {
       [self makeToast:@"分享成功" duration:0.3 position:CSToastPositionCenter];
       [self dismissShareViewAction];
    }
    
    - (void)wechatShareFailAction {
       [self makeToast:@"分享失败" duration:0.3 position:CSToastPositionCenter];
       [self dismissShareViewAction];
    }
    
    五、注意的细节
    • APPDelegate.m进行注册和设置回调
    // 1. APPDelegate.m里面注册
        BOOL isSuccess = [WXApi registerApp:WeiXinPayKey universalLink:WeiXinLinks];
    // 2. 设置分享后的回调
    - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
      if ([url.absoluteString containsString:[NSString stringWithFormat:@"%@://platformId=wechat", WeiXinPayKey]]) {
                return [WechatShareManager handleOpenUrl:url];
        }
        return YES;
    }
    // 3.适配iOS13
    - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
        NSURL *continueURL = userActivity.webpageURL;
        NSString *relativePath = continueURL.relativePath;
        if ([relativePath containsString:WeiXinPayKey] && [relativePath containsString:@"pay"]) {
            return [WXApi handleOpenUniversalLink:userActivity delegate:[WechatManager shareInstance]];
        } else if ([relativePath containsString:[NSString stringWithFormat:@"%@", WeiXinPayKey]]) {
            return [WXApi handleOpenUniversalLink:userActivity delegate:[WechatShareManager shareInstance]];
        }
        return YES;
    }
    

    相关文章

      网友评论

          本文标题:iOS集成微信分享

          本文链接:https://www.haomeiwen.com/subject/dhtuehtx.html