1. 程式人生 > >iOS開發之第三方分享微信分享、朋友圈分享,史上最新最全第三方分享微信方式實現、朋友圈方式實現

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"];
    return YES;
}

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)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;                <span style="font-family: Arial, Helvetica, sans-serif;"> //新增對appdelgate的微信分享的代理</span>
    BOOL isSuccess = [WXApi sendReq:sentMsg];
 
}


完整的程式碼如下:

appDelegate.h

#import <UIKit/UIKit.h>

@protocol WXDelegate <NSObject>

-(void)loginSuccessByCode:(NSString *)code;
-(void)shareSuccessByCode:(int) code;
@end

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, weak) id<WXDelegate> wxDelegate;
@end


appDelegate.m

#import "AppDelegate.h"
#import "WXApi.h"

//微信開發者ID
#define URL_APPID @"app id"




@interface AppDelegate ()<WXApiDelegate>


@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<NSString *,id> *)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/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 ()<WXDelegate>
{
    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的請求
    [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) {
       
    } 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


大功告成