1、添加微博依赖库
2.Appdelegate中添加代码
//SinaLogin
先到新浪微博开放平台申请appkey 设置回调网址(默认即可)
#define KAppKey @"542105907"
#define KRedirectURI @"https://api.weibo.com/oauth2/default.html"
[WeiboSDKenableDebugMode:YES];
[WeiboSDKregisterApp:KAppKey];
3、重写两个方法
//如果需要在Appdelegate中处理授权方法可以将delegate设为self,如果要再登陆界面处理可以将登陆界面设为代理
- (BOOL)application:(UIApplication *)application
handleOpenURL:(NSURL *)url
{
return [WeiboSDKhandleOpenURL:urldelegate:[LoginViewControllershareLogin]];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [WeiboSDKhandleOpenURL:urldelegate:[LoginViewControllershareLogin]];
}
3、在登陆界面书写登陆代码
#pragma mark -
#pragma mark 微博登陆
-(void)weiBoLoginMethod
{
WBAuthorizeRequest * request = [WBAuthorizeRequestrequest];
request.redirectURI =KRedirectURI;
request.scope =@"all";
[WeiboSDKsendRequest:request];
}
//授权代理方法
-(void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
NSLog(@"userInfo = %@",response.userInfo);
NSDictionary* userInfo = response.userInfo;
NSString* token = [userInfoobjectForKey:@"access_token"];
NSString* uid = [NSStringstringWithFormat:@"%@",[userInfoobjectForKey:@"uid"]];
if (token ==nil) {
UIAlertView* alert = [[UIAlertViewalloc]initWithTitle:@"登陆失败"message:@"请重新登陆"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil];
[alert show];
return;
}
//授权成功后通过收到的token和uid获取用户信息
NSMutableDictionary *params = [NSMutableDictionarydictionaryWithCapacity:2];
[params setObject:tokenforKey:@"access_token"];
[params setObject:uidforKey:@"uid"];
NSLog(@"params:%@", params);
WBHttpRequest * asiRequest = [WBHttpRequestrequestWithURL:@"https://api.weibo.com/2/users/show.json"httpMethod:@"GET"params:paramsdelegate:selfwithTag:@"getUserInfo"];
MBProgressHUD * hud = [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];
hud.labelText =@"收取用户信息..";
}
//获取用户信息方法
- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
NSError *error;
NSData *data = [resultdataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerializationJSONObjectWithData:dataoptions:kNilOptionserror:&error];
if (json ==nil)
{
NSLog(@"json parse failed \r\n");
return;
}
NSLog(@"json = %@",json);
//获取用户头像和昵称
NSString* screenname = [jsonobjectForKey:@"screen_name"];
NSString*picture = [jsonobjectForKey:@"profile_image_url"];
NSLog(@"usrName = %@",screenname);
NSLog(@"picture = %@",picture);
}