iOS学习笔记12—新浪微博分享

一.申请开发者账号,创建应用

http://open.t.sina.com.cn / 中申请成为开发者,再创建不同的应用,获得相应的 App Key  (在下面链接中的source即为app key)保存好好自己的

kAppKey   kAppSecret  kAppRedirectURI 

二.调用

1.下载官方的SDK解压 并将需要的文件拖到你的工程里面  需要导入的类库现在忘记了 大家应该可以能找到的吧


创建好分享界面


在Appdelegate.h中添加
#import <UIKit/UIKit.h>
#import "SinaWeibo.h"

#import "SinaWeiboRequest.h"
#import "FenXiangViewController.h"
//加入你申请的东西
#define kAppKey             @"******"
#define kAppSecret          @"*****"
#define kAppRedirectURI     @"*****"

#ifndef kAppKey
#error
#endif

#ifndef kAppSecret
#error
#endif

#ifndef kAppRedirectURI
#error
#endif


//#import "LogeViewController.h"
@class SinaWeibo;
@class RootViewController;
@class LogeViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate,SinaWeiboDelegate,SinaWeiboRequestDelegate>

{
    SinaWeibo *_sinaWeibo;
    
    FenXiangViewController *_viewController;
    
  
}
@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) FenXiangViewController *fenxiangviewController;
@property (readonly, nonatomic) SinaWeibo *sinaWeibo;


@end
在AppDelegate.m中添加
#import "AppDelegate.h"
#import "RootViewController.h"
#import "SinaWeibo.h"

@implementation AppDelegate
@synthesize sinaWeibo = _sinaWeibo;
@synthesize window = _window;
@synthesize fenxiangviewController = _fenxiangviewController;

- (void)dealloc
{
    [_sinaWeibo release];
    [_viewController release];
    [_window release];
    
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    self.window.backgroundColor = [UIColor whiteColor];


    //先初始化视图然后在把微博的delegate给视图
    _fenxiangviewController =[[FenXiangViewController alloc]init];
    
    _sinaWeibo = [[SinaWeibo alloc] initWithAppKey:kAppKey appSecret:kAppSecret appRedirectURI:kAppRedirectURI andDelegate:_fenxiangviewController];
    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"];
    }

    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [self.sinaWeibo applicationDidBecomeActive];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [self.sinaWeibo handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [self.sinaWeibo handleOpenURL:url];
}

则在分享界面.h文件中
#import <UIKit/UIKit.h>
#import "SinaWeibo.h"

#import "SinaWeiboRequest.h"

@class SinaWeibo;
@class RootViewController;
@class FenxiangViewController;

@interface FenXiangViewController : UIViewController<SinaWeiboDelegate,SinaWeiboRequestDelegate>
{
    UIButton *loginButton;
    UIButton *logoutButton;
    UIButton *userInfoButton;
    UIButton *timelineButton;
    UIButton *postStatusButton;
    UIButton *postImageStatusButton;
    
    NSDictionary *userInfo;
    NSArray *statuses;
    NSString *postStatusText;
    NSString *postImageStatusText;
    NSString *login;
    UIActivityIndicatorView *activity;
}

@property (readonly, nonatomic) SinaWeibo *sinaWeibo;

@property (nonatomic ,copy) NSString *string;
@property (nonatomic ,copy) NSString *name;
@property (nonatomic ,copy) NSString *place;
@property (strong, nonatomic) UIButton *shareButton;

@property (strong, nonatomic) UITextView *textView;
@property (strong, nonatomic) UIView *shareView;

@property (strong, nonatomic) UIActivityIndicatorView *indicator;


@end
.m文件

#import "FenXiangViewController.h"
#import "AppDelegate.h"
#import "SinaWeibo.h"
#define kAppKey             @"*****"
#define kAppSecret          @"*****"
#define kAppRedirectURL     @"****"


@interface FenXiangViewController ()

@end

@implementation FenXiangViewController

@synthesize shareButton = _shareButton;
@synthesize textView = _textView;
@synthesize shareView = _shareView;
@synthesize indicator = _indicator;

- (void)dealloc
{
    [userInfo release], userInfo = nil;
    [statuses release], statuses = nil;
    [postStatusText release], postStatusText = nil;
    [postImageStatusText release], postImageStatusText = nil;
    [activity release];
    [super dealloc];
}

- (SinaWeibo *)sinaweibo
{
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaWeibo;
}

- (void)removeAuthData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
}

- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    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)resetButtons
{
    [activity stopAnimating];
    //********************************************************************************
    SinaWeibo *sinaweibo = [self sinaweibo];
    BOOL authValid = sinaweibo.isAuthValid;
    
    loginButton.enabled = !authValid;
    logoutButton.enabled = authValid;
    userInfoButton.enabled = authValid;
    timelineButton.enabled = authValid;
    postStatusButton.enabled = authValid;
    postImageStatusButton.enabled = authValid;
    
    if (authValid)
    {
        [logoutButton setTitle:[NSString stringWithFormat:@"退出登录"] forState:UIControlStateNormal];
        if (userInfo)
        {
            [userInfoButton setTitle:[userInfo objectForKey:@"screen_name"] forState:UIControlStateNormal];
        }
        if (statuses)
        {
            if (statuses.count > 0)
            {
                [timelineButton setTitle:[[statuses objectAtIndex:0] objectForKey:@"text"] forState:UIControlStateNormal];
            }
            else
            {
                [timelineButton setTitle:@"no status" forState:UIControlStateNormal];
            }
        }
    }
    else
    {
        [logoutButton setTitle:@"退出登陆" forState:UIControlStateNormal];
        [userInfoButton setTitle:@"get user info" forState:UIControlStateNormal];
        [timelineButton setTitle:@"get timeline" forState:UIControlStateNormal];
    }
}

- (UIButton *)buttonWithFrame:(CGRect)frame action:(SEL)action
{
    UIImage *buttonBackgroundImage = [[UIImage imageNamed:@"button_background.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    UIImage *disabledButtonBackgroundImage = [[UIImage imageNamed:@"button_background_disabled.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundImage:buttonBackgroundImage forState:UIControlStateNormal];
    [button setBackgroundImage:disabledButtonBackgroundImage forState:UIControlStateDisabled];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    return button;
}

- (void)viewDidLoad
{
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImageView *logoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
    logoImageView.frame = CGRectMake(50, 40, 73, 30);
    [self.view addSubview:logoImageView];
    [logoImageView release];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"新浪微博分享";
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.frame = CGRectMake(140, 40, 140, 30);
    [self.view addSubview:titleLabel];
    [titleLabel release];

   login = [NSString stringWithFormat:@"登陆"];
    loginButton = [self buttonWithFrame:CGRectMake(20, 100, 280, 40) action:@selector(loginButtonPressed)];
    [loginButton setTitle:login forState:UIControlStateNormal];
    
    logoutButton = [self buttonWithFrame:CGRectMake(20, self.view.bounds.size.height-44-65, 280, 40) action:@selector(logoutButtonPressed)];
    [logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [logoutButton setTitle:@"退出登录" forState:UIControlStateDisabled];
    
    
    postImageStatusButton = [self buttonWithFrame:CGRectMake(20, 150, 280, 40) action:@selector(postImageStatusButtonPressed)];
    [postImageStatusButton setTitle:@"分享你的收藏" forState:UIControlStateNormal];
    
    [self resetButtons];
    
    
    activity=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [activity setFrame:CGRectMake(self.view.bounds.size.width/2-25, self.view.bounds.size.height/2-25, 50, 50)];
    [activity setColor:[UIColor grayColor]];
    [self.view addSubview:activity];

    [self.view setBackgroundColor:[UIColor colorWithRed:153.0/255 green:156.0/255 blue:238.0/255 alpha:1]];
    [super viewDidLoad];
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"back1.png"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0, 0, 30, 28)];
    UIBarButtonItem *backBar=[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem=backBar;
    [backBar release];
    
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loginButtonPressed
{
    [activity startAnimating];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; 
    [userInfo release], userInfo = nil;
    [statuses release], statuses = nil; 
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo logIn];
}

- (void)logoutButtonPressed
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo logOut];
}

- (void)userInfoButtonPressed
{
    //********************************************************************************
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo requestWithURL:@"users/show.json"
                       params:[NSMutableDictionary dictionaryWithObject:sinaweibo.userID forKey:@"uid"]
                   httpMethod:@"GET"
                     delegate:self];
}

- (void)postImageStatusButtonPressed
{
    //********************************************************************************
    if (!postImageStatusText)
    {
//        post_image_status_times ++;
        [postImageStatusText release], postImageStatusText = nil;
        postImageStatusText = [[NSString alloc] initWithFormat:@"%@", [NSDate date]];
    }
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:[NSString stringWithFormat:@"将要分享到新微博%@\n%@的%@很不错哦,有空一起玩?", postImageStatusText,_place,_name]
                                                       delegate:self cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
    alertView.tag = 1;
    [alertView show];
    [alertView release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    //********************************************************************************
    if (buttonIndex == 1)
    {
        if (alertView.tag == 0)
        {
            // post status    Hui.1
            SinaWeibo *sinaweibo = [self sinaweibo];
            [sinaweibo requestWithURL:@"statuses/update.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:postStatusText, @"status", nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if (alertView.tag == 1)
        {
            // post image status
            SinaWeibo *sinaweibo = [self sinaweibo];
         
            UIImage *image=[UIImage imageWithContentsOfFile:_string];
            [sinaweibo requestWithURL:@"statuses/upload.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postImageStatusText, @"status",
                                       image, @"pic", nil]
                           httpMethod:@"POST"
                             delegate:self];
        }
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

#pragma mark - SinaWeibo Delegate
//Hui 登陆 2
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    
    [self resetButtons];
    [self storeAuthData];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    [self removeAuthData];
    [self resetButtons];
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    [self removeAuthData];
    [self resetButtons];
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" failed!", postStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:[NSString stringWithFormat:@"发送微博成功 \"%@\"", postImageStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    
    [self resetButtons];
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    //Hui.2
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" succeed!", [result objectForKey:@"text"]]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postStatusText release], postStatusText = nil;
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                            message:[NSString stringWithFormat:@"发送失败 \"%@\" 请检查网络", [result objectForKey:@"text"]]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        
        [postImageStatusText release], postImageStatusText = nil;
    }
    
    [self resetButtons];
}

@end

最后需要在Supporting Files 里面的.plist配置文件里面加载


然后点击测试你的程序吧






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值