效果图:
//AppDelegate.h文件
//宏定义
#define kAppKey @"略"
#define kAppSecret @"略"
#define kAppRedirectURI @"略"
//属性设置
@property (readonly, nonatomic) SinaWeibo *sinaweibo;
//AppDelegate.m文件
#pragma mark - 集成新浪SDK
//创建新浪对象
_sinaweibo = [[SinaWeibo alloc] initWithAppKey:kAppKey appSecret:kAppSecret appRedirectURI:kAppRedirectURI andDelegate:self];
//存储数据
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *sinaweiboInfo = [defaults objectForKey:@"SinaWeiboAuthData"];
if ([sinaweiboInfo objectForKey:@"AccessTokenKey"] && [sinaweiboInfo objectForKey:@"ExpirationDateKey"] && [sinaweiboInfo objectForKey:@"UserIDKey"])
{
_sinaweibo.accessToken = [sinaweiboInfo objectForKey:@"AccessTokenKey"];
_sinaweibo.expirationDate = [sinaweiboInfo objectForKey:@"ExpirationDateKey"];
_sinaweibo.userID = [sinaweiboInfo objectForKey:@"UserIDKey"];
}
return YES;
}
//移除认证信息
- (void)removeAuthData {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
//保存认证数据
- (void)storeAuthData {
NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
_sinaweibo.accessToken, @"AccessTokenKey",
_sinaweibo.expirationDate, @"ExpirationDateKey",
_sinaweibo.userID, @"UserIDKey",
_sinaweibo.refreshToken, @"refresh_token", nil];
[[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweiboz {
NSLog(@"登陆成功");
[self storeAuthData];
}
- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo {
NSLog(@"注销");
[self removeAuthData];
}
在ViewController页面签订代理协议<SinaWeiboRequestDelegate>
在ViewDidLoad方法里添加下面一段代码
SinaWeibo *sina = [self sinaweibo];
if (sina.isAuthValid) {
//请求数据
[sina requestWithURL:@"statuses/friends_timeline.json" params:nil httpMethod:@"GET" delegate:self];
} else {
[sina logIn];
}
实现它的代理方法
#pragma mark -SinaWeiboRequestDelegate
- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error;{
NSLog(@"请求失败");
// NSLog(@"%@",error);
}
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result{
NSLog(@"请求成功");
NSArray *arr = result[@"statuses"];
}
//获取新浪微博对象
- (SinaWeibo *)sinaweibo
{
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
return delegate.sinaweibo;
}