第三方程序调用
下次使用时需要更新教案
第三方登录QQ
腾讯开放平台创建应用http://op.open.qq.com/manage_centerv2/ios?owner=897240781&uin=897240781
创建好之后我们可以获取到appID
之后点击上图中的《QQ登录》==》《应用调试者》填写测试QQ
下载SDK:http://wiki.open.qq.com/wiki/mobile/SDK%E4%B8%8B%E8%BD%BD
1、找到以下两个文件,拖入到工程中
2、托入工程后,添加需要的依赖库
3、修改必要的工程配置属性
在工程配置中的“Build Settings”一栏中找到“Linking”配置区,给“Other Linker Flags”配置项添加属性值“-fobjc-arc”
代码实现
在AppDelegate.m中 添加
#import
重新下面两个方法
在QQ登录界面声明一个TencentOAuth *tencentOAuth 对象,然后在QQ登录按钮的点击事件中
实现代理方法
#pragma mark -- TencentSessionDelegate
//登陆完成调用
- (void)tencentDidLogin
{
// resultLable.text = @"登录完成";
JYLog(@"登录完成");
if (tencentOAuth.accessToken && 0 != [tencentOAuth.accessToken length])
{
// 记录登录用户的OpenID、Token以及过期时间
// tokenLable.text = tencentOAuth.accessToken;
[tencentOAuth getUserInfo];
}
else
{
// tokenLable.text = @"登录不成功 没有获取accesstoken";
JYLog(@"登录不成功 没有获取accesstoken");
}
}
//非网络错误导致登录失败:
-(void)tencentDidNotLogin:(BOOL)cancelled
{
NSLog(@"tencentDidNotLogin");
if (cancelled)
{
// resultLable.text = @"用户取消登录";
JYLog(@"用户取消登录");
}else{
// resultLable.text = @"登录失败";
JYLog(@"登录失败");
}
}
// 网络错误导致登录失败:
-(void)tencentDidNotNetWork
{
NSLog(@"tencentDidNotNetWork");
// resultLable.text = @"无网络连接,请设置网络";
JYLog(@"无网络连接,请设置网络");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)getUserInfoResponse:(APIResponse *)response
{
NSLog(@"respons:%@",response.jsonResponse);
}
微信登录授权开发
1. 到微信开发平台注册相关APP,现在是等待审核成功后才能获取到对应的key和secret;获取成功后需要单独申请开通登录和支付接口,如图
2. 和QQ类似,需要填写Url Schemes,如demo中的wxd930ea5d5a258f4f ,然后引入相应framework
3. 在AppDelegate中注册和实现授权后的回调函数,代码如下:
//向微信注册
[WXApi registerApp:kWXAPP_ID withDescription:@"weixin"];
//授权后回调 WXApiDelegate
-(void)onResp:(BaseReq *)resp
{
/*
ErrCode ERR_OK = 0(用户同意)
ERR_AUTH_DENIED = -4(用户拒绝授权)
ERR_USER_CANCEL = -2(用户取消)
code 用户换取access_token的code,仅在ErrCode为0时有效
state 第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendReq时传入,由微信终端回传,state字符串长度不能超过1K
lang 微信客户端当前语言
country 微信用户当前国家信息
*/
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode== 0) {
NSString *code = aresp.code;
NSDictionary *dic = @{@"code":code};
}
}
//和QQ,新浪并列回调句柄
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [TencentOAuth HandleOpenURL:url] ||
[WeiboSDK handleOpenURL:url delegate:self] ||
[WXApi handleOpenURL:url delegate:self];;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [TencentOAuth HandleOpenURL:url] ||
[WeiboSDK handleOpenURL:url delegate:self] ||
[WXApi handleOpenURL:url delegate:self];;
}
}
4. 微信登录授权比较复杂,相比QQ,新浪多了几步,简单说就是需要三步,第一步,获取code,这个用来获取token,第二步,就是带上code获取token,第三步,根据第二步获取的token和openid来获取用户的相关信息;
下面用代码来实现:
第一步
- (IBAction)weixinLogin:(id)sender
{
[self sendAuthRequest];
}
-(void)sendAuthRequest
{
SendAuthReq* req =[[SendAuthReq alloc ] init];
req.scope = @"snsapi_userinfo,snsapi_base";
req.state = @"0744" ;
[WXApi sendReq:req];
}
这里获取后会调用之前在AppDelegate里面的对应oauthResp回调,获得得到的code。
第二步:token和openid
-(void)getAccess_token
{
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWXAPP_ID,kWXAPP_SECRET,self.wxCode.text];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *zoneUrl = [NSURL URLWithString:url];
NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
/*
{
"access_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWiusJMZwzQU8kXcnT1hNs_ykAFDfDEuNp6waj-bDdepEzooL_k1vb7EQzhP8plTbD0AgR8zCRi1It3eNS7yRyd5A";
"expires_in" = 7200;
openid = oyAaTjsDx7pl4Q42O3sDzDtA7gZs;
"refresh_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWi2ZzH_XfVVxZbmha9oSFnKAhFsS0iyARkXCa7zPu4MqVRdwyb8J16V8cWw7oNIff0l-5F-4-GJwD8MopmjHXKiA";
scope = "snsapi_userinfo,snsapi_base";
}
*/
self.access_token.text = [dic objectForKey:@"access_token"];
self.openid.text = [dic objectForKey:@"openid"];
}
});
});
}
利用GCD来获取对应的token和openID.
第三步:userinfo
-(void)getUserInfo
{
// https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.access_token.text,self.openid.text];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *zoneUrl = [NSURL URLWithString:url];
NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
/*
{
city = Haidian;
country = CN;
headimgurl = "http://wx.qlogo.cn/mmopen/FrdAUicrPIibcpGzxuD0kjfnvc2klwzQ62a1brlWq1sjNfWREia6W8Cf8kNCbErowsSUcGSIltXTqrhQgPEibYakpl5EokGMibMPU/0";
language = "zh_CN";
nickname = "xxx";
openid = oyAaTjsDx7pl4xxxxxxx;
privilege = (
);
province = Beijing;
sex = 1;
unionid = oyAaTjsxxxxxxQ42O3xxxxxxs;
}
*/
self.nickname.text = [dic objectForKey:@"nickname"];
self.wxHeadImg.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"headimgurl"]]]];
}
});
});
}
执行到这一步就算完成了整个授权登录的功能,能把昵称和头像显示出来,剩下的就是及时刷新你的token,详情可参考开发文档。
新浪微博登录
1、登录新浪微博开放平台,创建一个应用,获取APPID和APPKEY.
2、下载对应的SDK
1、导入SDK,配置工程
1、下载好SDK后,将SDK拖入工程
2、在工程中引入静态库之后,需要在编译时添加-ObjC,Target->Build Settings->Linking 下 Other Linker Flags 添加 -ObjC。(如果添加过了,就不需要重复添加了)
3、添加依赖库 (如果某些依赖库添加过了,就不需要重复添加了)
4、添加URL Schemes
2、添加相关代码
在AppDelegate.m 在添加头文件
#import "WeiboSDK.h"
添加协议
WeiboSDKDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[WeiboSDK registerApp:@"2045436852"];
return YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
if([[url scheme] hasPrefix:@"tencent"]) {
return [TencentOAuth HandleOpenURL:url];
}else if([[url scheme] hasPrefix:@"wx"]){
return [WXApi handleOpenURL:url delegate:self];
} else {
return [WeiboSDK handleOpenURL:url delegate:self];
}
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
if([[url scheme] hasPrefix:@"tencent"]) {
return [TencentOAuth HandleOpenURL:url];
} else if([[url scheme] hasPrefix:@"wx"]) {
return [WXApi handleOpenURL:url delegate:self];
} else {
return [WeiboSDK handleOpenURL:url delegate:self];
}
return YES;
}
在你需要调用新浪微博登录的按钮方法中添加代码:
WBMessageObject *message = [WBMessageObject message];
message.text = @"测试使用";
WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
[WeiboSDK sendRequest:request];