iOS 开发 第三方分享 微信朋友圈分享

微信分享前提:
1.需要成功在微信开发者平台注册了账号, 并取的对应的 appkey appSecret。
2.针对iOS9 添加了微信的白名单,以及设置了 scheme url 。 这都可以参照上面的链接,进行设置好。
3.分享不跳转的时候原因总结, 具体方法如下:
(1).首先检查下是否有向微信注册应用。
(2). 分享参数是否拼接错误。 监听下面 isSuccess yes为成功, no为是否, 看看是否是分享的对象弄错了。 文本对象与多媒体对象只能选一种。

BOOL isSuccess = [WXApi sendReq:sentMsg];
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {//向微信注册应用。 


      [WXApi registerApp:URL_APPID withDescription:@"wechat"];
 }
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options
{  
/*! @brief 处理微信通过URL启动App时传递的数据 * * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 * @param url 微信启动第三方应用时传递过来的URL * @param delegate WXApiDelegate对象,用来接收微信触发的消息。 * @return 成功返回YES,失败返回NO。 */

  return [WXApi handleOpenURL:url delegate:self]; 
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{ 
    return [WXApi handleOpenURL:url delegate:self];
}  

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{ 
    return [WXApi handleOpenURL:url delegate:self];

}

微信分享的核心代码;

#pragma mark 微信好友分享 
/** 
* 微信分享对象说明 
* 
* @param sender  
WXMediaMessage 多媒体内容分享 
WXImageObject 多媒体消息中包含的图片数据对象 
WXMusicObject 多媒体消息中包含的音乐数据对象 
WXVideoObject 多媒体消息中包含的视频数据对象 
WXWebpageObject 多媒体消息中包含的网页数据对象 
WXAppExtendObject 返回一个WXAppExtendObject对象 
WXEmoticonObject 多媒体消息中包含的表情数据对象 
WXFileObject 多媒体消息中包含的文件数据对象 
WXLocationObject 多媒体消息中包含的地理位置数据对象 
WXTextObject 多媒体消息中包含的文本数据对象  
*/ 


-(void)isShareToPengyouquan:(BOOL)isPengyouquan
{ 
/** 标题 
* @note 长度不能超过512字节 
*/ 

// @property (nonatomic, retain) NSString *title; 
/** 描述内容 
* @note 长度不能超过1K */ 

//@property (nonatomic, retain) NSString *description; 
/** 缩略图数据 
* @note 大小不能超过32K 
*/ 

// @property (nonatomic, retain) NSData *thumbData; 
/** 
* @note 长度不能超过64字节 */ 

// @property (nonatomic, retain) NSString *mediaTagName; 
/** 
* 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。 
*/ 

// @property (nonatomic, retain) id mediaObject;  

/*! @brief 设置消息缩略图的方法 
* 
* @param image 缩略图 
* @note 大小不能超过32K 
*/ 

//- (void) setThumbImage:(UIImage *)image; 
//缩略图 
UIImage *image = [UIImage imageNamed:@"消息中心 icon"]; 
WXMediaMessage *message = [WXMediaMessage message]; 
message.title = @"微信分享测试"; 
message.description = @"微信分享测试----描述信息"; 
//png图片压缩成data的方法,如果是jpg就要用 UIImageJPEGRepresentation message.thumbData = UIImagePNGRepresentation(image); 
[message setThumbImage:image];  


WXWebpageObject *ext = [WXWebpageObject object]; 
ext.webpageUrl = @"http://www.baidu.com"; 
message.mediaObject = ext; 
message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK"; 


SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc]init]; sentMsg.message = message; 
sentMsg.bText = NO; 

//选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline) 
if (isPengyouquan) { 
     sentMsg.scene = WXSceneTimeline; 
     //分享到朋友圈 } 
     else{ 
     sentMsg.scene = WXSceneSession; //分享到会话。 
}  


//如果我们想要监听是否成功分享,我们就要去appdelegate里面 找到他的回调方法 
// -(void) onResp:(BaseResp*)resp .我们可以自定义一个代理方法,然后把分享的结果返回回来。 
appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; 
appdelegate.wxDelegate = self; //添加对appdelgate的微信分享的代理 BOOL isSuccess = [WXApi sendReq:sentMsg];  
}

完整的代码如下:

appDelegate.h
#import   
@protocol WXDelegate   
-(void)loginSuccessByCode:(NSString *)code; 
-(void)shareSuccessByCode:(int) code; 
@end  

@interface AppDelegate : UIResponder   
@property (strong, nonatomic) UIWindow *window; 
@property (nonatomic, weak) id wxDelegate; 
@end

appDelegate.m
#import "AppDelegate.h" 
#import "WXApi.h"  //微信开发者ID 
#define URL_APPID @"app id"

@interface AppDelegate ()

@end    

@implementation AppDelegate   
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
     //向微信注册应用。 
     [WXApi registerApp:URL_APPID withDescription:@"wechat"]; 
     return YES; 
}  

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options
{  
     /*! @brief 处理微信通过URL启动App时传递的数据 
     * 
     * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 
     * @param url 微信启动第三方应用时传递过来的URL 
     * @param delegate WXApiDelegate对象,用来接收微信触发的消息。 
     * @return 成功返回YES,失败返回NO。
     */  
     return [WXApi handleOpenURL:url delegate:self];  
}   

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{ 
     return [WXApi handleOpenURL:url delegate:self];  
}  

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{ 
      return [WXApi handleOpenURL:url delegate:self]; 
}  

/*! 微信回调,不管是登录还是分享成功与否,都是走这个方法 
@brief 发送一个sendReq后,收到微信的回应 * 
* 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。 
* 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。 
* @param resp具体的回应内容,是自动释放的 
*/ 

-(void) onResp:(BaseResp*)resp
{ 
     NSLog(@"resp %d",resp.errCode);  
         /* enum WXErrCode 
         {  
         WXSuccess = 0, 成功  
         WXErrCodeCommon = -1, 普通错误类型  
         WXErrCodeUserCancel = -2, 用户点击取消并返回  
         WXErrCodeSentFail = -3, 发送失败  
         WXErrCodeAuthDeny = -4, 授权失败  
         WXErrCodeUnsupport = -5, 微信不支持  
         };  
         */  
   if ([resp isKindOfClass:[SendAuthResp class]])  
   {  
       //授权登录的类。  
       if (resp.errCode == 0)  
           {  
              //成功。  
              //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
              if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)])   
                 { SendAuthResp *resp2 = (SendAuthResp *)resp;  
                 [_wxDelegate loginSuccessByCode:resp2.code];  
                 }  
           }else{  
               //失败  
               NSLog(@"error %@",resp.errStr);  
               UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];  
               [alert show];  
               }  
    }   
    if ([resp isKindOfClass:[SendMessageToWXResp class]])  
       { //微信分享 微信回应给第三方应用程序的类  
          SendMessageToWXResp *response = (SendMessageToWXResp *)resp;  
          NSLog(@"error code %d error msg %@ lang %@ country %@",response.errCode,response.errStr,response.lang,response.country);   
          if (resp.errCode == 0)  
          { //成功。  
          //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
                if (_wxDelegate) {  
                       if([_wxDelegate respondsToSelector:@selector(shareSuccessByCode:)]){ 
                        [_wxDelegate shareSuccessByCode:response.errCode];  
                        }  
                }  
          }else{  
          //失败 NSLog(@"error %@",resp.errStr);  
          UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"分享失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];  
          [alert show];  
               }  
          }  
}  
@end 


ViewController.h
#import <UIkit.h>

@interface ViewController : UIViewController    

@end


ViewController.m

#import "ViewController.h" 
#import "WXApi.h" 
#import "AppDelegate.h" //微信开发者ID 
#define URL_APPID @"appid " 
#define URL_SECRET @"app secret" 
#import "AFNetworking.h" 

@interface ViewController () 

{ 
    AppDelegate *appdelegate;  

}  
@end   

@implementation ViewController   

- (void)viewDidLoad {  
       [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.  

}  

#pragma mark 微信登录  

- (IBAction)weixinLoginAction:(id)sender {   
        if ([WXApi isWXAppInstalled]) {  
            SendAuthReq *req = [[SendAuthReq alloc]init];  
            req.scope = @"snsapi_userinfo";  
            req.openID = URL_APPID; req.state = @"1245";  
            appdelegate = [UIApplication sharedApplication].delegate;  
            appdelegate.wxDelegate = self;   
            [WXApi sendReq:req];  
        }else{  
        //把微信登录的按钮隐藏掉。  
        }  
}  

#pragma mark 微信登录回调。  
-(void)loginSuccessByCode:(NSString *)code{  
        NSLog(@"code %@",code);  
        __weak typeof(*&self) weakSelf = self;   
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
        manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求  
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应  
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil];  
        //通过 appid secret 认证code . 来发送获取 access_token的请求  


        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {  
        //获得access_token,然后根据access_token获取用户信息请求。   
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
        NSLog(@"dic %@",dic);    
        /* access_token 接口调用凭证 expires_in    
        access_token接口调用凭证超时时间,单位(秒)  
        refresh_token   用户刷新  
        access_token openid 授权用户唯一标识  
        scope   用户授权的作用域,使用逗号(,)分隔  
        unionid 当且仅当该移动应用已获得该用户的 
        userinfo授权时,才会出现该字段  
        */  
        NSString *accessToken=[dic valueForKey:@"access_token"];  
        NSString* openID=[dic valueForKey:@"openid"];  
        [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];  
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
          NSLog(@"error %@",error.localizedFailureReason);  
    }];   
}    

-(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
        manager.requestSerializer = [AFJSONRequestSerializer serializer];  
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
        [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {   


} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {    
         NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; //开发人员拿到相关微信用户信息后, 需要与后台对接,进行登录  
         NSLog(@"login success dic ==== %@",dic);   
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
         NSLog(@"error %ld",(long)error.code);  
    }];  
}   



#pragma mark 微信好友分享  
/**  
* 微信分享对象说明 *  
* @param sender   
WXMediaMessage 多媒体内容分享  
WXImageObject 多媒体消息中包含的图片数据对象  
WXMusicObject 多媒体消息中包含的音乐数据对象  
WXVideoObject 多媒体消息中包含的视频数据对象  
WXWebpageObject 多媒体消息中包含的网页数据对象  
WXAppExtendObject 返回一个 
WXAppExtendObject对象  
WXEmoticonObject 多媒体消息中包含的表情数据对象  
WXFileObject 多媒体消息中包含的文件数据对象  
WXLocationObject 多媒体消息中包含的地理位置数据对象  
WXTextObject 多媒体消息中包含的文本数据对象   
*/  

- (IBAction)weixinShareAction:(id)sender {  
        [self isShareToPengyouquan:NO];   

}   

#pragma mark 微信朋友圈分享  

- (IBAction)friendShareAction:(id)sender {   
      [self isShareToPengyouquan:YES];  
}  

-(void)isShareToPengyouquan:(BOOL)isPengyouquan{  
         /** 标题 * @note 长度不能超过512字节 */  
         // @property (nonatomic, retain) NSString *title;  

         /** 描述内容 * @note 长度不能超过1K */  
         //@property (nonatomic, retain) NSString *description;  


         /** 缩略图数据  
         * @note 大小不能超过32K */  
         // @property (nonatomic, retain) NSData *thumbData;  


         /** * @note 长度不能超过64字节 */  
         // @property (nonatomic, retain) NSString *mediaTagName;  



         /** * 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。 */  
         // @property (nonatomic, retain) id mediaObject;   


        /*! @brief 设置消息缩略图的方法 *  
        * @param image 缩略图  
        * @note 大小不能超过32K */   
        //- (void) setThumbImage:(UIImage *)image;  

        //缩略图  
        UIImage *image = [UIImage imageNamed:@"消息中心 icon"];  
        WXMediaMessage *message = [WXMediaMessage message]; 
        message.title = @"微信分享测试";  
        message.description = @"微信分享测试----描述信息";  

        //png图片压缩成data的方法,如果是jpg就要用  
        UIImageJPEGRepresentation message.thumbData = UIImagePNGRepresentation(image);  
        [message setThumbImage:image];    
        WXWebpageObject *ext = [WXWebpageObject object];  
        ext.webpageUrl = @"http://www.baidu.com";  
        message.mediaObject = ext;  
        message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK";   
        SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc]init];  
        sentMsg.message = message;  
        sentMsg.bText = NO;  

        //选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)  
        if (isPengyouquan) {  
            sentMsg.scene = WXSceneTimeline; //分享到朋友圈  
        }else{  
            sentMsg.scene = WXSceneSession; //分享到会话。  
        }   


        //如果我们想要监听是否成功分享,我们就要去appdelegate里面 找到他的回调方法  
        // -(void) onResp:(BaseResp*)resp .我们可以自定义一个代理方法,然后把分享的结果返回回来。  

        appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;  
        appdelegate.wxDelegate = self;  
        BOOL isSuccess = [WXApi sendReq:sentMsg];   //添加对appdelgate的微信分享的代理   
}   


#pragma mark 监听微信分享是否成功 delegate  

-(void)shareSuccessByCode:(int)code{  
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"分享成功" message:[NSString stringWithFormat:@"reason : %d",code] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil]; [alert show];  

}     

- (void)didReceiveMemoryWarning {   
          [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.  
}   

@end

参考demo:
https://github.com/zhonggaorong/weixinLoginDemo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值