目录
如果已经有使用了友盟的话,改外海外版,授权可以使用facebook和twitter,google和ins需要单独使用,如果是直接就准备做海外版,强烈推荐使用Fierbase。
https://developers.google.cn/identity/sign-in/ios/sdk/
1.根据文档添加GoogleSignInDependencies.framework ,GoogleSignIn.framework ,GoogleSignIn.bundle如果不用官方按钮的话就不需要这个
2.根据文档添加依赖
3.生成client ID,点击绿色按钮,最后生成
static NSString * const kClientID =@"AAAA.apps.googleusercontent.com";
[GIDSignIn sharedInstance].clientID = kClientID;//用到的就是这个ID,生成的时候填写的bundleID需要建一个应用
4.填写URL Type保证跳转正常,格式为com.googleusercontent.apps.AAAA,AAAA就是生成kClientID的前半部分
5.代码部分
//
// CNMShareGoogle.h
// YoYoGame
//
// Created by gaoshuang on 2019/2/15.
// Copyright © 2019 SINASHOW. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <GoogleSignIn/GoogleSignIn.h>
@interface CNMShareGoogle : NSObject<CNMHelperProtocol>
/**
设置google Platform
*/
-(void)cnm_setupGooglePlatforms;
/**
设置googleDelegate
*/
-(void)cnm_setupGoogleDelegate;
/**
登录
*/
-(void)cnm_loginWithWithBlock:(void (^)(BOOL isSuccessed,GIDGoogleUser* userInfoResp))block;
/**
回调调转
@param url
@param sourceApplication
@param annotation
@return
*/
- (BOOL)cnm_handleURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation;
@end
//
// CNMShareGoogle.m
// YoYoGame
//
// Created by gaoshuang on 2019/2/15.
// Copyright © 2019 SINASHOW. All rights reserved.
//
#import "CNMShareGoogle.h"
//static NSString * const kClientID =
//@"589453917038-qaoga89fitj2ukrsq27ko56fimmojac6.apps.googleusercontent.com";
static NSString * const kClientID =
@"868607979203-2jjajqegiv7t5to8o69409fh6lvg9hcl.apps.googleusercontent.com";
@interface CNMShareGoogle()<GIDSignInDelegate, GIDSignInUIDelegate>
@property (copy, nonatomic)void (^blockLogin)(BOOL isSuccessed,GIDGoogleUser* userInfoResp);
@end
@implementation CNMShareGoogle
HELPER_SHARED(CNMShareGoogle)
-(void)cnm_setupGooglePlatforms{
[GIDSignIn sharedInstance].clientID = kClientID;
}
- (BOOL)cnm_handleURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation{
return [[GIDSignIn sharedInstance] handleURL:url
sourceApplication:sourceApplication
annotation:annotation];
return YES;
}
-(void)cnm_setupGoogleDelegate{
GIDSignIn *signIn = [GIDSignIn sharedInstance];
signIn.shouldFetchBasicProfile = YES;
signIn.delegate = self;
signIn.uiDelegate = self;
}
-(void)cnm_loginWithWithBlock:(void (^)(BOOL isSuccessed,GIDGoogleUser* userInfoResp))block{
self.blockLogin = nil;
self.blockLogin = block;
[[GIDSignIn sharedInstance] signIn];
}
#pragma mark - GIDSignDelegate
- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error {
// Perform any operations on signed in user here.
// NSString *userId = user.userID; // For client-side use only!
// NSString *idToken = user.authentication.idToken; // Safe to send to the server
// NSString *fullName = user.profile.name;
// NSString *givenName = user.profile.givenName;
// NSString *familyName = user.profile.familyName;
// NSString *email = user.profile.email;
//性别是取不到的,不需要根据acctoken取用户信息了
if (!error) {
if (self.blockLogin) {
self.blockLogin(YES,user);
}
}else{
if (self.blockLogin) {
self.blockLogin(NO,user);
}
}
// ...
}
- (void)signIn:(GIDSignIn *)signIn
didDisconnectWithUser:(GIDGoogleUser *)user
withError:(NSError *)error{
if (self.blockLogin) {
self.blockLogin(NO,user);
}
}
#pragma mark - GIDSignInUIDelegate
//该代理一般不用实现,除非自己对界面跳转或交互有一些需求
- (void)signInWillDispatch:(GIDSignIn *)signIn error:(NSError *)error {
// [myActivityIndicator stopAnimating];
}
// Present a view that prompts the user to sign in with Google
- (void)signIn:(GIDSignIn *)signIn
presentViewController:(UIViewController *)viewController {
[[self getCurrentVC] presentViewController:viewController animated:YES completion:nil];
}
// Dismiss the "Sign in with Google" view
- (void)signIn:(GIDSignIn *)signIn
dismissViewController:(UIViewController *)viewController {
[[self getCurrentVC] dismissViewControllerAnimated:YES completion:nil];
}
@end
关闭
流程,控制台添加应用,生成GoogleService-Info.list加入工程
控制台配置生产和发布证书
//需要外网环境才能返回
#pragma mark FIRMessagingDelegate
// [END ios_10_message_handling]
// [START refresh_token]
//获取注册令牌
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken
获取到令牌在控制台测试发消息
客户端获取令牌提交到服务器
https://www.jianshu.com/p/8281047bcdec
https://www.freesion.com/article/8801507287/
由于FaceBook使用到了友盟 传送门 (不建议混合使用,会很乱,海外版的直接用Firebase集成吧)
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logOut];//避免出现 FBSDK Login Error Code: 308
[login logInWithReadPermissions: @[@"public_profile",@"email"]
fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result,
NSError *error) {
if (error) {
NSLog(@"Process error");
} else if (result.isCancelled) {
NSLog(@"Cancelled");
} else {
NSLog(@"Logged in");
NSDictionary*params=[NSDictionary new];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:result.token.userID
parameters:params
HTTPMethod:@"GET"];
[request
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSString*name=[result objectForKey:@"name"];
NSString*userid=[result objectForKey:@"id"];
NSLog(@"name=%@ userID=%@ ",name,userid);
}];
}
}];
使用官方sdkdemo的分享 传送门
友盟分享统一调用
//sharWebUrl 一定得是https://标准格式,不然会跳转不进去,很坑,而且进入编辑界面点击返回键,放弃编辑,如果点击左上角返回应用会卡住
FBSDKShareLinkContent *linkContent = [[FBSDKShareLinkContent alloc] init];
linkContent.contentURL = [NSURL URLWithString:sharWebUrl];
linkContent.contentTitle = titile;
linkContent.contentDescription = content;
linkContent.imageURL = [NSURL URLWithString:imageUrl];
FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];
dialog.fromViewController = [self gs_getCurrentVC];
dialog.shareContent = linkContent;
BOOL isInstalled = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fbapi://"]];
if (isInstalled)
{
dialog.mode = FBSDKShareDialogModeNative;
}
else
{
dialog.mode = FBSDKShareDialogModeAutomatic;
}
[dialog show];
https://www.jianshu.com/p/dd35278ee0a3
使用官方sdkdemo 传送门
Twitter也使用到了友盟,但是友盟返回值中缺失authTokenSecret,需要手动掉用loadUserWithID方法
urltype设置 twitterkit-APPKEY
独立
Twitter 3.0 sdk的话
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[Twitter sharedInstance] startWithConsumerKey:@"guLppo4I" consumerSecret:@"xWpL85O3d3j6L0xTXC17j"];
return YES;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
// return [[Twitter sharedInstance] application:app openURL:url options:options];
if ([[Twitter sharedInstance] application:app openURL:url options:options]) {
return YES;
}
// If you handle other (non Twitter Kit) URLs elsewhere in your app, return YES. Otherwise
return NO;
}
//自定义xib按钮触发事件
- (IBAction)loginAction:(id)sender {
[[Twitter sharedInstance] logInWithCompletion:^(TWTRSession * _Nullable session, NSError * _Nullable error) {
if(session){
NSLog(@"%@已登录",session.userName);
[self loadTwitterUserWithID:session.userID];
} else {
NSLog(@"error:%@",error.localizedDescription);
}
}];
}
//获取Twitter用户信息
- (void)loadTwitterUserWithID:(NSString *)userId{
TWTRAPIClient *client = [TWTRAPIClient clientWithCurrentUser];
[client loadUserWithID:userId completion:^(TWTRUser * _Nullable user, NSError * _Nullable error) {
if (user) {
NSLog(@"头像url:%@",user.profileImageURL);
}else{
NSLog(@"error:%@",error.localizedDescription);
}
}];
}
//管理多个用户时需要注销用户
- (void)logoutTwitterUser{
TWTRSessionStore *store = [[Twitter sharedInstance] sessionStore];
NSString *userID = store.session.userID;
[store logOutUserID:userID];
}
https://www.jianshu.com/p/50f67bd865ac
NSString* strDescription =@"用DataYuk,邂逅属于你的爱,快来相亲,交友,谈恋爱吧";
NSString* strWebURL = @"https://winkydate.com";
// Example
NSMutableArray *parameter = [NSMutableArray array];
if (![strDescription isEqualToString:@""]) {
[parameter addObject:[NSString stringWithFormat:@"text=%@", strDescription]];
}
if (![strWebURL isEqualToString:@""]) {
[parameter addObject:[NSString stringWithFormat:@"url=%@", strWebURL]];
}
NSString *shareWebLink = [[NSString stringWithFormat:@"https://twitter.com/intent/tweet?%@",
[parameter componentsJoinedByString:@"&"]]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:shareWebLink]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:shareWebLink]];
}
return;
// //检查是否当前会话具有登录的用户
// if ([[Twitter sharedInstance].sessionStore hasLoggedInUsers]) {
// TWTRComposer *composer = [[TWTRComposer alloc] init];
// [composer setText:messageObject.text];
// //带图片方法
// [composer setImage: shareObject.thumbImage ];
// [composer setURL:[NSURL URLWithString:@"https://winkydate.com"]];
// [composer showFromViewController:self completion:^(TWTRComposerResult result){
// if(result == TWTRComposerResultCancelled) {
// //分享失败
// }else{
// //分享成功
// }
// }];
// }else{
// [[Twitter sharedInstance] logInWithCompletion:^(TWTRSession *session, NSError *error) {
// if (session) {
// TWTRComposer *composer = [[TWTRComposer alloc] init];
// [composer setText:messageObject.text];
// //带图片方法
// [composer setImage: shareObject.thumbImage ];
// [composer setURL:[NSURL URLWithString:@"https://winkydate.com"]];
// [composer showFromViewController:self completion:^(TWTRComposerResult result){
// if(result == TWTRComposerResultCancelled) {
// //分享失败
// }else{
// //分享成功
// }
// }];
// NSLog(@"signed in as %@", [session userName]);
// } else {
// NSLog(@"error: %@", [error localizedDescription]);
// }
// }];
// }
// [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_Twitter messageObject:messageObject currentViewController:[self gs_getCurrentVC] completion:^(id data, NSError *error) {
// if (error) {
// // [[self gs_getCurrentVC] showToast:error.userInfo[@"message"]];
// }else{
// [[self gs_getCurrentVC] showToast:gs_language(@"分享成功")];
// }
// }];
https://www.jianshu.com/p/4ccdb3a6dc67
https://www.jianshu.com/p/2d8992a278f4
https://www.jianshu.com/p/50f67bd865ac
Instagram官方文档
#import <UIKit/UIKit.h>
@interface UserModel: NSObject
@property (strong, nonatomic)NSString* full_name;
@property (strong, nonatomic)NSString* idD;
@property (strong, nonatomic)NSString* is_business;
@property (strong, nonatomic)NSString* profile_picture;
@property (strong, nonatomic)NSString* username;
@property (strong, nonatomic)NSString* website;
@property (strong, nonatomic)NSString* access_token;
@end
@interface IKLoginViewController : UIViewController
@property (strong, nonatomic)void (^Block)(BOOL isSuccessed, UserModel* model);
@end
#import "IKLoginViewController.h"
#import <WebKit/WebKit.h>
@implementation UserModel
@end
@interface IKLoginViewController () <WKNavigationDelegate>
@end
@implementation IKLoginViewController
- (void)viewDidLoad
{
[super viewDidLoad];
WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
webConfiguration.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webConfiguration];
webView.scrollView.bounces = NO;
self.navigationItem.title = @"Instagram";
[self.navigationItem.rightBarButtonItem setEnabled:NO];
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.instagram.com/oauth/authorize/?client_id=%@&redirect_uri=%@&response_type=code",@"883a3fe2c91f45a38a4354c82a9da7a3",@"http://www.funplanet.cn/"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.view addSubview:webView];
webView.navigationDelegate = self;
[webView loadRequest:request];
}
- (void)authenticationSuccess
{
[self.navigationItem setLeftBarButtonItem:nil];
[self.navigationItem.rightBarButtonItem setEnabled:YES];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
if ([navigationResponse.response.URL.absoluteString hasPrefix:@"http://www.funplanet.cn/?code="]){
}
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler
{
NSString* str =navigationAction.request.URL.absoluteString;
if ([navigationAction.request.URL.absoluteString hasPrefix:@"http://www.funplanet.cn/?code="]){
str = [str substringFromIndex:[str rangeOfString:@"code="].location+5];
NSDictionary* dict = @{@"client_id":@"883a3fe2c91f45a38a43AAAAA",//应用id,登录的测试账号需要被邀请加入沙盒环境,或者用审核应用id的账号
@"client_secret":@"345f20582ed343e8a494f20BBBBB",//应用私钥
@"code":[str toString],//重定向后取到的codeid
@"grant_type":@"authorization_code",//固定的值
@"redirect_uri":@"http://www.funplanet.cn/"//固定回调的url
};
[self POSTDictionary:@"https://api.instagram.com/oauth/access_token" params:dict tag:1 HTTPS:YES success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
UserModel* model = [[UserModel alloc]init];
model.access_token =responseObject[@"access_token"];
model.full_name =responseObject[@"user"][@"full_name"];
model.idD = [responseObject[@"user"][@"id"] toString];
model.is_business =responseObject[@"user"][@"is_business"];
model.profile_picture =responseObject[@"user"][@"profile_picture"];
model.username =responseObject[@"user"][@"username"];
if (_Block) {
_Block(YES, model);
[self popCanvas];
}
}else{
if (_Block) {
_Block(NO, nil);
[self popCanvas];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (_Block) {
_Block(NO, nil);
[self popCanvas];
}
}];
decisionHandler(WKNavigationActionPolicyCancel);
}
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
// if ([navigationResponse.response.URL.absoluteString hasPrefix:@"http://www.funplanet.cn/?code="]){
//
// }
}
@end
Instagram 唤起不了客户端,只能网页进行,退出登录的方法
WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
[dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
for (WKWebsiteDataRecord *record in records)
{
if ( [record.displayName containsString:@"instagram.com"]) //取消备注,可以针对某域名清除,否则是全清
{
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes
forDataRecords:@[record]
completionHandler:^{
NSLog(@"Cookies for %@ deleted successfully",record.displayName);
}];
}
}
}];
NSString *shareWebLink = [NSString stringWithFormat:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:shareWebLink]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:shareWebLink]];
}
另外有进入发布页面选择相册以及固定相册图片的方法
Google https://developers.google.cn/identity/sign-in/ios/sdk/
FaceBook https://github.com/facebook/facebook-ios-sdk
编译需要添加一个空的swift文件(Swift module的问题)
如果遇上Redefinition of module 'Swift',建议重新pod一下
Twitter https://github.com/twitter-archive/twitter-kit-ios
ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. 传送门