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

微信分享前提:html

  1.須要成功在微信開發者平臺註冊了帳號, 並取的對應的 appkey appSecret。web

        2. 針對iOS9 添加了微信的白名單,以及設置了 scheme url 。 這均可以參照上面的連接,進行設置好。 json

  3. 分享不跳轉的時候緣由總結, 具體方法以下:api

             1. 首先檢查下是否有向微信註冊應用。微信

       2. 分享參數是否拼接錯誤。 監聽下面 isSuccess  yes爲成功, no爲是否, 看看是不是分享的對象弄錯了。 文本對象與多媒體對象只能選一種。微信開發

[objc] view plain copyapp

 

  1. BOOL isSuccess = [WXApi sendReq:sentMsg];  

 

 

[objc] view plain copyide

 

  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 copyatom

 

  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  

源碼下載地址:http://www.jinhusns.com/Products/Download

相關文章
相關標籤/搜索