第一步:在腾讯开放平台注册应用,获取应用的appID以及AppSecret。
第二步:在腾讯开放平台下载sdk,并导入进项目。(详细步骤看官方文档wiki.open.qq.com/wiki/mobile…
第三步:配置 URL Scheme 在Xcode中,选择你的工程设置项,选中TARGETS一栏,在info标签栏的URL type添加URL scheme为你所注册的应用程序id.
第四步:开始编写代码
//在appdelegate.h中引用qq头文件
\
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//重写openURL方法
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
return [TencentOAuth HandleOpenURL:url];
}
\
1.在调用界面
\
调用代理 TencentSessionDelegate
{
TencentOAuth *tencentOAuth;
NSArray *permissions;
}
\
- (void)viewDidLoad {
\
tencentOAuth=[[TencentOAuth alloc]initWithAppId:@"你的appid"andDelegate:self];
permissions= [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t", nil ];
}
\
//QQ登录按钮
\
-(void)QQbuttonClick{
[tencentOAuth authorize:permissions inSafari:NO];
}
#pragma mark -- TencentSessionDelegate
//登陆完成调用
- (void)tencentDidLogin
{
[self showMessage:@"登录完成"];
if (tencentOAuth.accessToken && 0 != [tencentOAuth.accessToken length])
{
// 记录登录用户的OpenID、Token以及过期时间
[tencentOAuth getUserInfo];
}
else
{
NSLog(@"--登录不成功 没有获取accesstoken");
}
}
\
//非网络错误导致登录失败:
-(void)tencentDidNotLogin:(BOOL)cancelled
{
NSLog(@"tencentDidNotLogin");
if (cancelled)
{
NSLog(@"用户取消登录");
}else{
NSLog(@"登录失败");
}
}
// 网络错误导致登录失败:
-(void)tencentDidNotNetWork
{
NSLog(@"tencentDidNotNetWork");
}
//获取用户信息
-(void)getUserInfoResponse:(APIResponse *)response
{
NSLog(@"respons:%@",response.jsonResponse);
}
\
- (BOOL)tencentNeedPerformIncrAuth:(TencentOAuth *)tencentOAuth withPermissions:(NSArray *)permissions
{
// incrAuthWithPermissions是增 授权时需要调 的登录接
// permissions是需要增 授权的权限 表
[tencentOAuth incrAuthWithPermissions:permissions];
// 返回NO表明 需要再回传未授权API接 的原始请求结果;否则可以返回YES return NO;
return NO;
}
//增 授权成功时,会通过tencentDidUpdate:协议接 通知第三 应 :
- (void)tencentDidUpdate:(TencentOAuth *)tencentOAuth
{
NSLog(@"增 授权完成");
if (tencentOAuth.accessToken&& 0 != [tencentOAuth.accessToken length])
{
// 在这 第三 应 需要 新 维护的token及有效期限等信息
// 务必在这 检查 户的openid是否有变 ,变 需重新拉取 户的资 等信息 _labelAccessToken.text = tencentOAuth.accessToken;
}
else
{
NSLog(@"增 授权 成功,没有获取accesstoken");
}
}
//增 授权失败时,会通过tencentFailedUpdate:协议接 通知第三 应 :
- (void)tencentFailedUpdate:(UpdateFailType)reason
{
switch (reason) { case kUpdateFailNetwork: {
NSLog(@"增 授权失败, 络连接,请设置 络");
break; }
case kUpdateFailUserCancel: {
NSLog(@"增 授权失败, 户取消授权");
break; }
case kUpdateFailUnknown: default:
{
NSLog(@"增 授权失败,未知错误");
break; }
}
}