iOS微博登录与分享

前言:由于公司需要、要求此次三方登录全部用官方SDK,需要配置友盟和ShareSDK的同学,这篇文章帮不上太多忙,看一下就好。

1、集成SDK
1.1、(手动集成)下载并解压SDK​:下载链接,并将GitHub上下载的libWeiboSDK文件夹导入项目中。
1.2、(通过CocoaPods集成)
pod "WeiboSDK"

2、添加依赖库(CocoaPods集成的不用添加)
QuartzCore.framework、
ImageIO.framework、
SystemConfiguration.framework、
Security.framework、
CoreTelephony.framework、
CoreText.framework、
UIKit.framework、
Foundation.framework、
CoreGraphics.framework、
libz.tbd、
libsqlite3.tbd

3、新增⼀一条URL Scheme:选中⼯工程Target -> Info -> URLTypes;
identifier随便写,URL scheme写成wb +App Key(如wb23232323232)。

iOS微博登录与分享_第1张图片
微博URL scheme

4、添加⽩白名单:LSApplicationQueriesSchemes新增⽩名单****

微博白名单

5、AppDelegate中向微博注册Appid,并添加处理回调的代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [WeiboSDK registerApp:WBAppid];
     return YES;
}

//iOS9.0以前使用

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    [WeiboSDK handleOpenURL:url delegate:[WBApiManager sharedManager]];
return YES;
}

// 9.0以后使用新API接口

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options{
    [WeiboSDK handleOpenURL:url delegate:[WBApiManager sharedManager]];
    return YES;
}

代理在哪个类实现的回调方法 就写哪个类就行了。
以上集成配置 微博登录和微博分享是一样的,做一遍操作即可。

1、微博登录

//微博不能授权次数过多,否则很容易失败,所以授权以后本地保存一下,如果下次登录时已经有授权信息,直接调用获取用户信息接口就行了。(如果真的授权次数太多提示授权失败了,可以重装APP,还能再授权几次。)
- (void)SinaLogin{
    //授权过 直接获取用户信息
    if (![BMWFactory isBlankString:[BMWUserDefaults objectForKey:WBAccess_token]] && ![BMWFactory isBlankString:[BMWUserDefaults objectForKey:WBUid]]) {
        NSString *WBAccess_tokenStr = [BMWUserDefaults objectForKey:WBAccess_token];
        NSString *WBUidStr = [BMWUserDefaults objectForKey:WBUid];
        NSDictionary *dict = @{@"access_token":WBAccess_tokenStr,@"uid":WBUidStr};
        [self getWBUserInfoData:dict];
    }else{
        //发送授权请求
        WBApiManager *manager = [WBApiManager sharedManager];
        manager.wBApiManagerDelegate = self;
        WBAuthorizeRequest *request = [WBAuthorizeRequest request];
        //回调地址与 新浪微博开放平台中 我的应用  --- 应用信息 -----高级应用    -----授权设置 ---应用回调中的url保持一致就好了
        request.redirectURI = WBAppUrl;
        //SCOPE 授权说明参考  http://open.weibo.com/wiki/
        request.scope = @"all";
        request.userInfo = nil;
        [WeiboSDK sendRequest:request];
    }

}
//微博授权后 获取用户信息
- (void)getWBUserInfoData:(NSDictionary *)dict{
    __weak typeof(self) weakSelf = self;
    [[BMWAFNetworkingManager shareManager] GET:@"https://api.weibo.com/2/users/show.json" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = (NSDictionary *)responseObject;
                [SVProgressHUD showSuccessWithStatus:@"用户信息获取成功"];
        NSString *sex;
        if ([dic[@"gender"] isEqualToString:@"m"]) {
            sex = @"1";
        }else if ([dic[@"gender"] isEqualToString:@"f"]){
            sex = @"2";
        }else{
            sex = @"0";
        }
        NSDictionary *LoginDataDic = @{@"uid":dic[@"id"],@"idstr":dic[@"idstr"],@"nickname":dic[@"screen_name"],@"headimgurl":dic[@"avatar_large"],@"sex":sex};
        //微博用户信息获取成功,调用后台微博登录接口
        [weakSelf getWBLoginData:LoginDataDic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
    
}

如果还未授过权,则在此代理中先获取授权信息,然后再调用获取微博用户信息接口

#pragma mark - WBApiManagerDelegate======================微博回调代理================WBApiManagerDelegate
-(void)weiboLoginByResponse:(WBBaseResponse *)response{
    //回调成功,吊起登录接口
    SLog(@"微博登录授权成功");
    NSDictionary *dic = (NSDictionary *) response.requestUserInfo;
    NSLog(@"userinfo %@",dic);
    if (![BMWFactory isBlankDictionary:dic]) {
        if (![BMWFactory isBlankString:dic[@"access_token"]] || ![BMWFactory isBlankString:dic[@"uid"]]) {
            NSString *access_token = dic[@"access_token"];
            NSString *uid = dic[@"uid"];
            NSDictionary *dict = @{@"access_token":access_token,@"uid":uid};
            //保存回调的数据
            [BMWUserDefaults setObject:dic[@"access_token"] forKey:WBAccess_token];
            [BMWUserDefaults setObject:dic[@"uid"] forKey:WBUid];
            //获取用户信息
            [self getWBUserInfoData:dict];
        }
    }else{
      NSString *access_token = [(WBAuthorizeResponse *)response accessToken];
        NSString *uid = [(WBAuthorizeResponse *)response userID];
        NSDictionary *dict = @{@"access_token":access_token,@"uid":uid};
//保存回调的数据
        [BMWUserDefaults setObject:access_token forKey:WBAccess_token];
        [BMWUserDefaults setObject:uid forKey:WBUid];
        //获取用户信息
        [self getWBUserInfoData:dict];
    }
}

以上是微博登录
以下是微博分享

2、微博分享

- (void)WeiBoShare{
    WBApiManager *manager = [WBApiManager sharedManager];
    manager.wBApiManagerDelegate = self;
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    //回调地址与 新浪微博开放平台中 我的应用  --- 应用信息 -----高级应用    -----授权设置 ---应用回调中的url保持一致就好了
    authRequest.redirectURI = WBAppUrl;
    //SCOPE 授权说明参考  http://open.weibo.com/wiki/
    authRequest.scope = @"all";
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:nil];
    request.userInfo = @{@"ShareMessageFrom": @"ViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    
    [WeiboSDK sendRequest:request];
}
- (WBMessageObject *)messageToShare
{
//    //分享文字和图片
    WBMessageObject *message = [WBMessageObject message];
//    message.text = shareTitleStr;
//    WBImageObject *image = [WBImageObject object];
//        image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"123456" ofType:@"jpg"]];
//    image.imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:shareImageStr]];
//    message.imageObject = image;
    //分享多媒体文件
    WBWebpageObject *webpage = [WBWebpageObject object];
    webpage.objectID = @"identifier1";
    //链接
    webpage.title = shareDetailStr;
    //描述
    webpage.description = shareDetailStr;
    UIImage *thumbnailImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:shareImageStr]]];
   UIImage *newImage = [BMWFactory imageWithImage:thumbnailImage scaledToSize:CGSizeMake(50, 50)];
    //图片
    webpage.thumbnailData = UIImageJPEGRepresentation(newImage, 0.1);
    //链接
    webpage.webpageUrl = shareUrlStr;
    message.mediaObject = webpage;
    return message;
}
#pragma mark - WBApiManagerDelegate====================WBApiManagerDelegate
-(void)weiboShareSuccessCode:(NSInteger)shareResultCode{
    [SVProgressHUD showSuccessWithStatus:@"分享成功!"];
}

你可能感兴趣的:(iOS微博登录与分享)