iOS开发 OC版本 微信分享的实战流程 以及 一些代码和界面封装

53 阅读4分钟

前情:最近老项目需要添加微信分享的功能,因为是老项目所以是OC编写的。所以这里分享下开发微信分享的一个流程。

1:首先需要在微信开放平台注册你的应用:open.weixin.qq.com

2:OK 你注册成功后需要用到的是 appid 以及 你注册应用时自己填写的 Universal Links。好的,都获取到了,那我们开始项目代码中的配置

(1):首先用cocoapods 终端引入我们需要的库:

           pod 'WechatOpenSDK'

(2):配置info.plist 文件:

​编辑

(3):

《1》:在AppDelegate.h 中引入   这里是我的 AppDelegate.h 内容

#import <UIKit/UIKit.h>

#import "WXApi.h"

//下方这里是用协议代理方法实现的一个分享状态的回调(你也可以用block方式实现,block相对好用些)

@protocol WXAuthDelegate 

@optional

-(void)wxShareSuccessd:(NSString *)Type;

@end

//

@interface AppDelegate : UIResponder 

@property (nonatomicassignid delegate;

@end

《2》:这里是AppDelegate.m 中的内容(这里不全粘贴了 我将有用的挑出来 你可以直接粘贴到你的

.m文件中):

首相需要  注册你的app 

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  //向微信注册

    [WXApi registerApp:@"wx689eeb576a727467" universalLink:@"https://tfpt_teacher/app/"];

 return YES;

}

  • (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {

 return[WXApi handleOpenURL:url delegate:self];

}

  • (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

 return [WXApi handleOpenURL:url delegate:self];

}

//这里是微信库里的方法的回调

-(void) onResp:(BaseResp*)resp{

 if([resp isKindOfClass:[SendMessageToWXResp class]]) //判断这里是分享功能

    {

        NSString *strTitle = [NSString stringWithFormat:@"提示"];

        NSString *strMsg;

 if (resp.errCode == 0) {

            //成功

 if (self.delegate && [self.delegate respondsToSelector: @selector(wxShareSuccessd:)])

[self.delegate wxShareSuccessd:@"0"];

            strMsg = [NSString stringWithFormat:@"分享成功"];

}else if (resp.errCode == -2){

            //取消 分享

 if (self.delegate && [self.delegate respondsToSelector: @selector(wxShareSuccessd:)])

[self.delegate wxShareSuccessd:@"-2"];

            strMsg = [NSString stringWithFormat:@"取消分享"];            

}else{

            //失败

 if (self.delegate && [self.delegate respondsToSelector: @selector(wxShareSuccessd:)])

[self.delegate wxShareSuccessd:@"-1"];

            strMsg = [NSString stringWithFormat:@"分享失败,请重试"];

        }

}else{

        //微信其他功能 如登录等的判断

  }

}

(4):接下来是在你要实现点击分享的界面里:

例如我这的是LJFMainVC里

#import "LJFMainVC.h"

#import "AppDelegate.h"  //引入AppDelegate.h

#import "ShareKindView.h" //我自己封装的用于分享的view 具体分享的设置在这里面,下面会贴出实现代码 ,你复制到你项目的时候 图标会不显示,请你自己添加图标。

@interface LJFMainVC ()  //遵守协议

//点击分享按钮 弹出选择分享微信好友 还是 朋友圈

-(void)shareClick{

 if (self.ShareKindV == nil) {

 self.ShareKindV = [[ShareKindView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

    }    

 self.ShareKindV.shareTitle = @" ***";

 self.ShareKindV.shareDescripTion = @"*** ";

 self.ShareKindV.sharePath = [NSString stringWithFormat:@"***"];

 self.ShareKindV.ShareImageNameStr = @"share微信.png";

 //下面这里是如引用,防止内存泄露

 __weak __typeof(self)  weakSelf  = self;

 self.ShareKindV.failOpenWXBlock = ^{

        [weakSelf.view makeToast:@"请安装微信后重试!"];

    };

[self.tabBarController.view addSubview:self.ShareKindV];

}

//这里是实现代理方法 成功的消息会从 appdelegate.m 的协议方法中传到这

-(void)wxShareSuccessd:(NSString *)Type{

 if ([Type isEqualToString:@"0"]) {

        //分享成功的处理

}else{

 //分享失败的处理

    }

}

(4):那么下面就是分享界面的封装了直接粘贴代码吧 (你可复制使用)

这里是 .h 文件

#import <UIKit/UIKit.h>

#import "WXApi.h"

NS_ASSUME_NONNULL_BEGIN

@interface ShareKindView : UIView

@property (nonatomic,strong) NSString * ShareImageNameStr;

@property (nonatomic,strong) NSString * sharePath;

@property (nonatomic,strong) NSString * shareTitle;

@property (nonatomic,strong) NSString * shareDescripTion;

@property (nonatomic,copyvoid(^failOpenWXBlock)(void);

@end

NS_ASSUME_NONNULL_END

下面这里是.m文件

#import "ShareKindView.h"

@implementation ShareKindView

-(id)initWithFrame:(CGRect)frame{

 self = [super initWithFrame:frame];

 if (self) {

 self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.7];

[self presetUI];

    }

 return self;

}

-(void)presetUI{

    UIView * BottomPickView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-190,SCREEN_WIDTH, 190)];

    BottomPickView.backgroundColor = COLOR_WITH_HEX(0xF8F8F7);

[self addSubview:BottomPickView];

     [CYtools yp_setCornerRadiusWithView:BottomPickView radius:20 positions:@[@1,@2]];

    UILabel * titlelbale = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, 200, 40)];

    [titlelbale setCenterX:SCREEN_WIDTH/2];

    titlelbale.text = @"分享到";

    titlelbale.textColor = COLOR_WITH_HEX(0x222222);

    titlelbale.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];

    titlelbale.textAlignment = NSTextAlignmentCenter;

    [BottomPickView addSubview:titlelbale];

 for (int i = 0; i<2; i++) {

        UIButton * pickBtn = [UIButton buttonWithType:UIButtonTypeCustom];

        [pickBtn setFrame:CGRectMake(0, 30, 150, 150)];

        pickBtn.tag = 666666+i;

 if (i == 0) {

            [pickBtn setCenterX:SCREEN_WIDTH/4];

            [pickBtn setImage:[UIImage imageNamed:@"share微信"] forState:UIControlStateNormal];

            [pickBtn setTitle:@"微信好友" forState:UIControlStateNormal];

[pickBtn addTarget:self action: @selector(FriendPick) forControlEvents:UIControlEventTouchUpInside];

}else{

            [pickBtn setCenterX:SCREEN_WIDTH/4*3];

            [pickBtn setImage:[UIImage imageNamed:@"share朋友圈"] forState:UIControlStateNormal];

            [pickBtn setTitle:@"微信朋友圈" forState:UIControlStateNormal];

[pickBtn addTarget:self action: @selector(FriendQuanPick) forControlEvents:UIControlEventTouchUpInside];

        }

        pickBtn.titleLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];

        pickBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;

        [pickBtn setTitleColor:COLOR_WITH_HEX(0x222222) forState:UIControlStateNormal];

        [CYtools adjustButtonImageViewUPTitleDownWithButton:pickBtn];

        [BottomPickView addSubview:pickBtn];

    }

}

-(void)FriendPick{

    //判断是否安装了微信

 if ([WXApi isWXAppInstalled]) {

[self ShareKindPick:@"friend"];

}else{

[self makeToast:@"请安装微信后再试"];

[self removeFromSuperview];

    }

}

-(void)FriendQuanPick{

    //判断是否安装了微信

 if ([WXApi isWXAppInstalled]) {

[self ShareKindPick:@"Quan"];

}else{

[self makeToast:@"请安装微信后再试"];

 if (self.failOpenWXBlock) {

 self.failOpenWXBlock();

        }        

[self removeFromSuperview];

    }

}

-(void)ShareKindPick:(NSString *)Type{

 if (self.ShareImageNameStr.length>0) {

[self shareImageWithType:Type];

}else{

[self sharePathWith_SPath:self.sharePath andTitle:self.shareTitle andDescriptionStr:self.shareDescripTion andType:Type];

    }

}

//分享一个链接

-(void)sharePathWith_SPath:(NSString *)Path andTitle:(NSString *)titleStr andDescriptionStr:(NSString *)descripStr andType:(NSString *)Type{

    WXWebpageObject * pageObject = [WXWebpageObject object];

    pageObject.webpageUrl = Path;

    WXMediaMessage *message = [WXMediaMessage message];

    message.title = titleStr;

    message.description = descripStr;

    [message setThumbImage:[UIImage imageNamed:@"sharePathHeader"]];

    message.mediaObject = pageObject;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];

req.bText = NO;

    req.message = message;

//    req.text = Path;

 if ([Type isEqualToString:@"friend"]) {

        req.scene = WXSceneSession;

}else{

        req.scene = WXSceneTimeline;

    }

[WXApi sendReq:req completion:nil];

[self removeFromSuperview];

}

//我这里分享的是图片 如果你分享的是文字,网络连接等请看上面那个方法或者去开放平台官方查看参数设置

-(void)shareImageWithType:(NSString *)Type{

UIImage *image = [UIImage imageNamed:self.ShareImageNameStr];

   NSData * imageData = UIImageJPEGRepresentation(image, 0.7);

    WXImageObject *imageObject = [WXImageObject object];

    imageObject.imageData = imageData;

    WXMediaMessage *message = [WXMediaMessage message];

    //这里是新添加的一个参数  作用官方文档里有写 并不会显示在分享内容中

NSString *filePath = [[NSBundle mainBundle] pathForResource:self.ShareImageNameStr

                                                         ofType:@"png"];

    message.thumbData = [NSData dataWithContentsOfFile:filePath];

    message.mediaObject = imageObject;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];

req.bText = NO;

    req.message = message;

 if ([Type isEqualToString:@"friend"]) {

        req.scene = WXSceneSession;

}else{

        req.scene = WXSceneTimeline;

    }

[WXApi sendReq:req completion:nil];

[self removeFromSuperview];

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[self removeFromSuperview];

}

@end

OK!!!!结束 希望对你有所帮助,喜欢的点个赞和关注吧!!你的鼓励是我更新最大的动力