你的位置:首页 > 软件开发 > 操作系统 > iOS开发之第三方分享微信分享、朋友圈分享,史上最新最全

iOS开发之第三方分享微信分享、朋友圈分享,史上最新最全

发布时间:2017-11-14 11:00:11
微信分享前提: 1.需要成功在微信开发者平台注册了账号, 并取的对应的 appkey appSecret。 2. 针对iOS9 添加了微信的白名单,以及设置了 scheme url 。 这都可以参照上面的链接,进行设置好。 3. 分 ...

微信分享前提:

  1.需要成功在微信开发者平台注册了账号, 并取的对应的 appkey appSecret。

        2. 针对iOS9 添加了微信的白名单,以及设置了 scheme url 。 这都可以参照上面的链接,进行设置好。 

  3. 分享不跳转的时候原因总结, 具体方法如下:

             1. 首先检查下是否有向微信注册应用。

       2. 分享参数是否拼接错误。 监听下面 isSuccess  yes为成功, no为是否, 看看是否是分享的对象弄错了。 文本对象与多媒体对象只能选一种。

[objc] view plain copy 
  1. BOOL isSuccess = [WXApi sendReq:sentMsg];  

 

 

[objc] view plain copy 
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  2.       
  3.     //向微信注册应用。  
  4.     [WXApi registerApp:URL_APPID withDescription:@"wechat"];  
  5.     return YES;  
  6. }  
  7.   
  8. -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{  
  9.       
  10.     /*! @brief 处理微信通过URL启动App时传递的数据 
  11.      * 
  12.      * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 
  13.      * @param url 微信启动第三方应用时传递过来的URL 
  14.      * @param delegate  WXApiDelegate对象,用来接收微信触发的消息。 
  15.      * @return 成功返回YES,失败返回NO。 
  16.      */  
  17.       
  18.     return [WXApi handleOpenURL:url delegate:self];  
  19. }  
  20.   
  21.   
  22. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{  
  23.     return [WXApi handleOpenURL:url delegate:self];  
  24. }  
  25.   
  26. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation{  
  27.     return [WXApi handleOpenURL:url delegate:self];  
  28. }  

 

 

微信分享的核心代码;

 

[objc] view plain copy 
  1. #pragma mark 微信好友分享  
  2. /** 
  3.  *  微信分享对象说明 
  4.  * 
  5.  *  @param sender  
  6. WXMediaMessage    多媒体内容分享 
  7. WXImageObject      多媒体消息中包含的图片数据对象 
  8. WXMusicObject      多媒体消息中包含的音乐数据对象 
  9. WXVideoObject      多媒体消息中包含的视频数据对象 
  10. WXWebpageObject    多媒体消息中包含的网页数据对象 
  11. WXAppExtendObject  返回一个WXAppExtendObject对象 
  12. WXEmoticonObject   多媒体消息中包含的表情数据对象 
  13. WXFileObject       多媒体消息中包含的文件数据对象 
  14. WXLocationObject   多媒体消息中包含的地理位置数据对象 
  15. WXTextObject       多媒体消息中包含的文本数据对象 
  16.   
  17.  */  
  18.   
  19. -(void)isShareToPengyouquan:(BOOL)isPengyouquan{  
  20.     /** 标题 
  21.      * @note 长度不能超过512字节 
  22.      */  
  23.     // @property (nonatomic, retain) NSString *title;  
  24.     /** 描述内容 
  25.      * @note 长度不能超过1K 
  26.      */  
  27.     //@property (nonatomic, retain) NSString *description;  
  28.     /** 缩略图数据 
  29.      * @note 大小不能超过32K 
  30.      */  
  31.     //  @property (nonatomic, retain) NSData   *thumbData;  
  32.     /** 
  33.      * @note 长度不能超过64字节 
  34.      */  
  35.     // @property (nonatomic, retain) NSString *mediaTagName;  
  36.     /** 
  37.      * 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。 
  38.      */  
  39.     // @property (nonatomic, retain) id        mediaObject;  
  40.       
  41.     /*! @brief 设置消息缩略图的方法 
  42.      * 
  43.      * @param image 缩略图 
  44.      * @note 大小不能超过32K 
  45.      */  
  46.     //- (void) setThumbImage:(UIImage *)image;  
  47.     //缩略图  
  48.     UIImage *image = [UIImage imageNamed:@"消息中心 icon"];  
  49.     WXMediaMessage *message = [WXMediaMessage message];  
  50.     message.title = @"微信分享测试";  
  51.     message.description = @"微信分享测试----描述信息";  
  52.     //png图片压缩成data的方法,如果是jpg就要用 UIImageJPEGRepresentation  
  53.     message.thumbData = UIImagePNGRepresentation(image);  
  54.     [message setThumbImage:image];  
  55.       
  56.   
  57.     WXWebpageObject *ext = [WXWebpageObject object];  
  58.     ext.webpageUrl = @"http://www.baidu.com";  
  59.     message.mediaObject = ext;  
  60.     message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK";  
  61.       
  62.     SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc]init];  
  63.     sentMsg.message = message;  
  64.     sentMsg.bText = NO;  
  65.     //选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)  
  66.     if (isPengyouquan) {  
  67.         sentMsg.scene = WXSceneTimeline;  //分享到朋友圈  
  68.     }else{  
  69.         sentMsg.scene =  WXSceneSession;  //分享到会话。  
  70.     }  
  71.       
  72.     //如果我们想要监听是否成功分享,我们就要去appdelegate里面 找到他的回调方法  
  73.     // -(void) onResp:(BaseResp*)resp .我们可以自定义一个代理方法,然后把分享的结果返回回来。  
  74.     appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;  
  75.     appdelegate.wxDelegate = self;                <span style="font-family: Arial, Helvetica, sans-serif;"> //添加对appdelgate的微信分享的代理</span>  
  76.     BOOL isSuccess = [WXApi sendReq:sentMsg];  
  77.    
  78. }  



 

完整的代码如下:

appDelegate.h

 

[objc] view plain copy 
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @protocol WXDelegate <NSObject>  
  4.   
  5. -(void)loginSuccessByCode:(NSString *)code;  
  6. -(void)shareSuccessByCode:(int) code;  
  7. @end  
  8.   
  9. @interface AppDelegate : UIResponder <UIApplicationDelegate>  
  10.   
  11. @property (strong, nonatomic) UIWindow *window;  
  12. @property (nonatomic, weak) id<WXDelegate> wxDelegate;  
  13. @end  



 

appDelegate.m

 

[objc] view plain copy 
  1. #import "AppDelegate.h"  
  2. #import "WXApi.h"  
  3.   
  4. //微信开发者ID  
  5. #define URL_APPID @"app id"  
  6.   
  7.   
  8.   
  9.   
  10. @interface AppDelegate ()<WXApiDelegate>  
  11.   
  12.   
  13. @end  
  14.   
  15.   
  16.   
  17. @implementation AppDelegate  
  18.   
  19.   
  20. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  21.       
  22.     //向微信注册应用。  
  23.     [WXApi registerApp:URL_APPID withDescription:@"wechat"];  
  24.     return YES;  
  25. }  
  26.   
  27. -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{  
  28.       
  29.     /*! @brief 处理微信通过URL启动App时传递的数据 
  30.      * 
  31.      * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 
  32.      * @param url 微信启动第三方应用时传递过来的URL 
  33.      * @param delegate  WXApiDelegate对象,用来接收微信触发的消息。 
  34.      * @return 成功返回YES,失败返回NO。 
  35.      */  
  36.       
  37.     return [WXApi handleOpenURL:url delegate:self];  
  38. }  
  39.   
  40.   
  41. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{  
  42.     return [WXApi handleOpenURL:url delegate:self];  
  43. }  
  44.   
  45. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation{  
  46.     return [WXApi handleOpenURL:url delegate:self];  
  47. }  
  48.   
  49. /*! 微信回调,不管是登录还是分享成功与否,都是走这个方法 @brief 发送一个sendReq后,收到微信的回应 
  50.  * 
  51.  * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。 
  52.  * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。 
  53.  * @param resp具体的回应内容,是自动释放的 
  54.  */  
  55. -(void) onResp:(BaseResp*)resp{  
  56.     NSLog(@"resp %d",resp.errCode);  
  57.       
  58.     /* 
  59.     enum  WXErrCode { 
  60.         WXSuccess           = 0,    成功 
  61.         WXErrCodeCommon     = -1,  普通错误类型 
  62.         WXErrCodeUserCancel = -2,    用户点击取消并返回 
  63.         WXErrCodeSentFail   = -3,   发送失败 
  64.         WXErrCodeAuthDeny   = -4,    授权失败 
  65.         WXErrCodeUnsupport  = -5,   微信不支持 
  66.     }; 
  67.     */  
  68.     if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。  
  69.         if (resp.errCode == 0) {  //成功。  
  70.             //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
  71.             if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {  
  72.                 SendAuthResp *resp2 = (SendAuthResp *)resp;  
  73.                 [_wxDelegate loginSuccessByCode:resp2.code];  
  74.             }  
  75.         }else{ //失败  
  76.             NSLog(@"error %@",resp.errStr);  
  77.             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
  78.             [alert show];  
  79.         }  
  80.     }  
  81.       
  82.     if ([resp isKindOfClass:[SendMessageToWXResp class]]) { //微信分享 微信回应给第三方应用程序的类  
  83.         SendMessageToWXResp *response = (SendMessageToWXResp *)resp;  
  84.         NSLog(@"error code %d  error msg %@  lang %@   country %@",response.errCode,response.errStr,response.lang,response.country);  
  85.           
  86.         if (resp.errCode == 0) {  //成功。  
  87.             //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
  88.             if (_wxDelegate) {  
  89.                 if([_wxDelegate respondsToSelector:@selector(shareSuccessByCode:)]){  
  90.                     [_wxDelegate shareSuccessByCode:response.errCode];  
  91.                 }  
  92.             }  
  93.         }else{ //失败  
  94.             NSLog(@"error %@",resp.errStr);  
  95.             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"分享失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
  96.             [alert show];  
  97.         }  
  98.     }  
  99. } @end  

 

 

ViewController.h

 

[objc] view plain copy 
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewController : UIViewController  
  4.   
  5.   
  6. @end  



 

ViewController.m

 

[objc] view plain copy 
    1. #import "ViewController.h"  
    2. #import "WXApi.h"  
    3. #import "AppDelegate.h"  
    4. //微信开发者ID  
    5. #define URL_APPID @"appid "  
    6. #define URL_SECRET @"app secret"  
    7. #import "AFNetworking.h"  
    8. @interface ViewController ()<WXDelegate>  
    9. {  
    10.     AppDelegate *appdelegate;  
    11. }  
    12. @end  
    13.   
    14. @implementation ViewController  
    15.   
    16. - (void)viewDidLoad {  
    17.     [super viewDidLoad];  
    18.     // Do any additional setup after loading the view, typically from a nib.  
    19. }  
    20. #pragma mark 微信登录  
    21. - (IBAction)weixinLoginAction:(id)sender {  
    22.       
    23.     if ([WXApi isWXAppInstalled]) {  
    24.         SendAuthReq *req = [[SendAuthReq alloc]init];  
    25.         req.scope = @"snsapi_userinfo";  
    26.         req.openID = URL_APPID;  
    27.         req.state = @"1245";  
    28.         appdelegate = [UIApplication sharedApplication].delegate;  
    29.         appdelegate.wxDelegate = self;  
    30.   
    31.         [WXApi sendReq:req];  
    32.     }else{  
    33.         //把微信登录的按钮隐藏掉。  
    34.     }  
    35. }  
    36. #pragma mark 微信登录回调。  
    37. -(void)loginSuccessByCode:(NSString *)code{  
    38.     NSLog(@"code %@",code);  
    39.     __weak typeof(*&self) weakSelf = self;  
    40.       
    41.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
    42.     manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求  
    43.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应  
    44.     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil nil];  
    45.     //通过 appid  secret 认证code . 来发送获取 access_token的请求  
    46.     [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",URL_APPID,URL_SECRET,code] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {  
    47.          
    48.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token,然后根据access_token获取用户信息请求。  
    49.   
    50.         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
    51.         NSLog(@"dic %@",dic);  
    52.           
    53.         /* 
    54.          access_token   接口调用凭证 
    55.          expires_in access_token接口调用凭证超时时间,单位(秒) 
    56.          refresh_token  用户刷新access_token 
    57.          openid 授权用户唯一标识 
    58.          scope  用户授权的作用域,使用逗号(,)分隔 
    59.          unionid     当且仅当该移动应用已获得该用户的userinfo授权时,才会出现该字段 
    60.          */  
    61.         NSString* accessToken=[dic valueForKey:@"access_token"];  
    62.         NSString* openID=[dic valueForKey:@"openid"];  
    63.         [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];  
    64.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
    65.      NSLog(@"error %@",error.localizedFailureReason);  
    66.     }];  
    67.       
    68. }  
    69.   
    70. -(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{  
    71.       
    72.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
    73.     manager.requestSerializer = [AFJSONRequestSerializer serializer];  
    74.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
    75.     [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {  
    76.           
    77.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  
    78.         NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
    79.         //开发人员拿到相关微信用户信息后, 需要与后台对接,进行登录  
    80.         NSLog(@"login success dic  ==== %@",dic);  
    81.           
    82.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
    83.         NSLog(@"error %ld",(long)error.code);  
    84.     }];  
    85. }  
    86.   
    87. #pragma mark 微信好友分享  
    88. /** 
    89.  *  微信分享对象说明 
    90.  * 
    91.  *  @param sender  
    92. WXMediaMessage    多媒体内容分享 
    93. WXImageObject      多媒体消息中包含的图片数据对象 
    94. WXMusicObject      多媒体消息中包含的音乐数据对象 
    95. WXVideoObject      多媒体消息中包含的视频数据对象 
    96. WXWebpageObject    多媒体消息中包含的网页数据对象 
    97. WXAppExtendObject  返回一个WXAppExtendObject对象 
    98. WXEmoticonObject   多媒体消息中包含的表情数据对象 
    99. WXFileObject       多媒体消息中包含的文件数据对象 
    100. WXLocationObject   多媒体消息中包含的地理位置数据对象 
    101. WXTextObject       多媒体消息中包含的文本数据对象 
    102.   
    103.  */  
    104. - (IBAction)weixinShareAction:(id)sender {  
    105.  [self isShareToPengyouquan:NO];  
    106.       
    107. }  
    108.   
    109. #pragma mark 微信朋友圈分享  
    110. - (IBAction)friendShareAction:(id)sender {  
    111.       
    112.     [self isShareToPengyouquan:YES];  
    113. }  
    114. -(void)isShareToPengyouquan:(BOOL)isPengyouquan{  
    115.     /** 标题 
    116.      * @note 长度不能超过512字节 
    117.      */  
    118.     // @property (nonatomic, retain) NSString *title;  
    119.     /** 描述内容 
    120.      * @note 长度不能超过1K 
    121.      */  
    122.     //@property (nonatomic, retain) NSString *description;  
    123.     /** 缩略图数据 
    124.      * @note 大小不能超过32K 
    125.      */  
    126.     //  @property (nonatomic, retain) NSData   *thumbData;  
    127.     /** 
    128.      * @note 长度不能超过64字节 
    129.      */  
    130.     // @property (nonatomic, retain) NSString *mediaTagName;  
    131.     /** 
    132.      * 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。 
    133.      */  
    134.     // @property (nonatomic, retain) id        mediaObject;  
    135.       
    136.     /*! @brief 设置消息缩略图的方法 
    137.      * 
    138.      * @param image 缩略图 
    139.      * @note 大小不能超过32K 
    140.      */  
    141.     //- (void) setThumbImage:(UIImage *)image;  
    142.     //缩略图  
    143.     UIImage *image = [UIImage imageNamed:@"消息中心 icon"];  
    144.     WXMediaMessage *message = [WXMediaMessage message];  
    145.     message.title = @"微信分享测试";  
    146.     message.description = @"微信分享测试----描述信息";  
    147.     //png图片压缩成data的方法,如果是jpg就要用 UIImageJPEGRepresentation  
    148.     message.thumbData = UIImagePNGRepresentation(image);  
    149.     [message setThumbImage:image];  
    150.       
    151.   
    152.     WXWebpageObject *ext = [WXWebpageObject object];  
    153.     ext.webpageUrl = @"http://www.baidu.com";  
    154.     message.mediaObject = ext;  
    155.     message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK";  
    156.       
    157.     SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc]init];  
    158.     sentMsg.message = message;  
    159.     sentMsg.bText = NO;  
    160.     //选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)  
    161.     if (isPengyouquan) {  
    162.         sentMsg.scene = WXSceneTimeline;  //分享到朋友圈  
    163.     }else{  
    164.         sentMsg.scene =  WXSceneSession;  //分享到会话。  
    165.     }  
    166.       
    167.     //如果我们想要监听是否成功分享,我们就要去appdelegate里面 找到他的回调方法  
    168.     // -(void) onResp:(BaseResp*)resp .我们可以自定义一个代理方法,然后把分享的结果返回回来。  
    169.     appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;  
    170.     appdelegate.wxDelegate = self;  
    171.     BOOL isSuccess = [WXApi sendReq:sentMsg];  
    172.       
    173.       
    174.     //添加对appdelgate的微信分享的代理  
    175.       
    176. }  
    177.   
    178. #pragma mark 监听微信分享是否成功 delegate  
    179. -(void)shareSuccessByCode:(int)code{  
    180.     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"分享成功" message:[NSString stringWithFormat:@"reason : %d",code] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
    181.     [alert show];  
    182. }  
    183.   
    184.   
    185.   
    186. - (void)didReceiveMemoryWarning {  
    187.     [super didReceiveMemoryWarning];  
    188.     // Dispose of any resources that can be recreated.  
    189. }  
    190.   
    191. @end  

源码下载地址

原标题:iOS开发之第三方分享微信分享、朋友圈分享,史上最新最全

关键词:IOS

IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。