从零开始iOS实用编程技巧iOS 开发

iOS-微信的登录与分享

2016-04-10  本文已影响4623人  BestVast

微信登录与分享
微信开发平台-移动应用微信登录开发指南
1、首先导入微信的SDK


2、导入需要的framework


3、添加URL Type

4、在plist文件里添加iOS9 URL Schemes 白名单
<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>wechat</string>
        <string>weixin</string>
        <string>sinaweibohd</string>
        <string>sinaweibo</string>
        <string>sinaweibosso</string>
        <string>weibosdk</string>
        <string>weibosdk2.5</string>
        <string>mqqapi</string>
        <string>mqq</string>
        <string>mqqOpensdkSSoLogin</string>
        <string>mqqconnect</string>
        <string>mqqopensdkdataline</string>
        <string>mqqopensdkgrouptribeshare</string>
        <string>mqqopensdkfriend</string>
        <string>mqqopensdkapi</string>
        <string>mqqopensdkapiV2</string>
        <string>mqqopensdkapiV3</string>
        <string>mqzoneopensdk</string>
        <string>wtloginmqq</string>
        <string>wtloginmqq2</string>
        <string>mqqwpa</string>
        <string>mqzone</string>
        <string>mqzonev2</string>
        <string>mqzoneshare</string>
        <string>wtloginqzone</string>
        <string>mqzonewx</string>
        <string>mqzoneopensdkapiV2</string>
        <string>mqzoneopensdkapi19</string>
        <string>mqzoneopensdkapi</string>
        <string>mqzoneopensdk</string>
        <string>alipay</string>
        <string>alipayshare</string>
    </array>

5、向微信终端程序注册第三方应用,并在第三方应用实现从微信返回
在AppDelegate.m中引入”WXApi.h"头文件,然后写入如下:

#import "WXApi.h"
#import "WXApiObject.h"
@interface AppDelegate ()<WXApiDelegate>  //添加代理

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [WXApi registerApp:@"WX_AppID" withDescription:@"weixin"];
    return YES;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    
    [WXApi handleOpenURL:url delegate:self];
    
    return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [WXApi handleOpenURL:url delegate:self];  
    return YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
     [WXApi handleOpenURL:url delegate:self];
    return YES;
}

6、微信分享—>在控制器里面添加分享代码

#import "WXApiObject.h"
#import “WXApi.h"

//分享文字给好友 
       SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.text = @"测试把信息分享到微信好友";
        req.bText = YES;
        req.scene = WXSceneSession;//会话(WXSceneSession)或者朋友圈(WXSceneTimeline)
        
        [WXApi sendReq:req];
    
//分享图片给好友
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = @"测试把图片分享到微信好友";
        [message setThumbImage:[UIImage imageNamed:@"IconWX.png"]];
        WXImageObject *imageObject = [[WXImageObject alloc] init];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"IconWX" ofType:@"png"];
        imageObject.imageData = [NSData dataWithContentsOfFile:filePath];
        message.mediaObject = imageObject;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;        
        [WXApi sendReq:req];

   //分享网页给好友
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = @"测试把web分享到微信好友";
        [message setThumbImage:[UIImage imageNamed:@"IconWX.png"]];
        
        WXWebpageObject *webObject = [WXWebpageObject object];
        webObject.webpageUrl = @"http://www.baidu.com";
        message.mediaObject = webObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        
        [WXApi sendReq:req];
   
 //分享文字到朋友圈
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.text = @"测试把信息分享到微信朋友圈";
        req.bText = YES;
        req.scene = WXSceneTimeline;//会话(WXSceneSession)或者朋友圈(WXSceneTimeline)
        [WXApi sendReq:req];

 //分享图片到朋友圈 
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = @"测试把图片分享到微信朋友圈";
        [message setThumbImage:[UIImage imageNamed:@"IconWX.png"]];
        WXImageObject *imageObject = [[WXImageObject alloc] init];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"IconWX" ofType:@"png"];
        imageObject.imageData = [NSData dataWithContentsOfFile:filePath];
        message.mediaObject = imageObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        
        [WXApi sendReq:req];
  
//分享网页到朋友圈
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = @"测试把web分享到微信朋友圈";
        message.description = @"";
        [message setThumbImage:[UIImage imageNamed:@"IconWX.png"]];
        
        WXWebpageObject *webObject = [WXWebpageObject object];
        webObject.webpageUrl = @"http://www.baidu.com";
        message.mediaObject = webObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        
        [WXApi sendReq:req];

6.1、分享App消息到微信,微信点击之后能够跳转到App

static NSString *kAPPContentTitle = @"App消息";
static NSString *kAPPContentDescription = @"这种消息只有App自己才能理解,由App指定打开方式";
static NSString *kAppContentExInfo = @"<xml>extend info</xml>";
static NSString *kAppContnetExURL = @"http://weixin.qq.com";
static NSString *kAppMessageExt = @"这是第三方带的测试字段";
static NSString *kAppMessageAction = @"<action>dotaliTest</action>";

//分享本App识别的信息(会从微信调整到本App)
        Byte* pBuffer = (Byte *)malloc(1024*100);
        memset(pBuffer, 0, 1024*100);
        NSData* data = [NSData dataWithBytes:pBuffer length:1024*100];
        free(pBuffer);
        
        UIImage *thumbImage = [UIImage imageNamed:@"res2.jpg"];
        
        WXAppExtendObject *ext = [WXAppExtendObject object];
        ext.extInfo = kAppContentExInfo;
        ext.url = kAppContnetExURL;
        ext.fileData = data;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = kAPPContentTitle;
        message.description = kAPPContentDescription;
        message.mediaObject = ext;
        message.messageExt = kAppMessageExt;
        message.messageAction = kAppMessageAction;
        message.mediaTagName = nil;
        [message setThumbImage:thumbImage];
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.scene = WXSceneSession;
        req.message = message;
        
        [WXApi sendReq:req];

7、微信登陆 —>在AppDelegate里面添加登陆成功的通知

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *rep = (SendAuthResp *)resp;
        if (rep.errCode == 0) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:WXLoginSuccess object:@{@"code":rep.code}];
        }
        
    }

8、微信登陆 —>在控制器里面添加登陆代码

static NSString *kAuthScope = @"snsapi_userinfo";
static NSString *kAuthOpenID = @"这个我现在没使用";
static NSString *kAuthState = @"123";
//微信登陆
- (void)onClickBtn
{
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = kAuthScope;
    req.state = kAuthState;
    req.openID = kAuthOpenID;
    [WXApi sendReq:req];
}

9、微信登陆—>在控制器里面实现登陆成功之后的回调

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXLogin:) name:WXLoginSuccess object:nil];

//登陆成功之后获取token
- (void)WXLogin:(NSNotification *)notifi
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage GET:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:@{@"appid":WX_AppID, @"secret":WX_AppSecret, @"code":notifi.object[@"code"], @"grant_type":@"authorization_code"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        /*"access_token" = "OezXcEiiBSKSxW0eoylIeBPKSgTfwua1QABCnleka9CqGYr9J4wP2NHLDEFTP0vqsiS4DFDyXNQmYSaM6dW1s8MrQi6NSC9dV6ZqqjazKWQv3kfeozrm-fbZTXU80vLaWYflw07nkDhmX3KJHsEVxQ";
         "expires_in" = 7200;
         openid = xxxxxxxxxxxxxxxxxxxxxxxxxx;
         "refresh_token" = "OezXcEiiBSKSxW0eoylIeBPKSgTfwua1QABCnleka9CqGYr9J4wP2NHLDEFTP0vq6O1ZVOcyb8uL5dLrcuRaydRmY9BcYgJeOLqRjlLyp5HpBlYc2Ikja-RFm6ghGQ32r_iZfQfAQhtEqwk9ibf8vA";
         scope = "snsapi_userinfo";
         unionid = o4bo2vzI0vCvGTa11GBMkx0SbcwQ;*/
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:WXSaveToken];
        [self saveTokenAndRequireWXInfo];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"access_token error-->%@", error.localizedDescription);
    }];
}

10、微信登陆—>在控制器里面通过token请求得到微信部分个人信息

- (void)saveTokenAndRequireWXInfo
{
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:WXSaveToken];
   AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage GET:@"https://api.weixin.qq.com/sns/userinfo" parameters:@{@"openid":dict[@"openid"], @"access_token":dict[@"access_token"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",dict);
//        {
//            city = "xxx";
//            country = xxx;
//            headimgurl = “http://wx.qlogo.cn/mmopen/xxxxxxx/0”;
//            language = "zh_CN";
//            nickname = xxx;
//            openid = xxxxxxxxxxxxxxxxxxx; //授权用户唯一标识
//            privilege =     (
//            );
//            province = "xxx";
//            sex = 0;
//            unionid = xxxxxxxxxxxxxxxxxx;
//        }
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:WXResponse_UserInfo];       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"userinfo error-->%@", error.localizedDescription);
    }];     }

上一篇下一篇

猜你喜欢

热点阅读