2

iPhone アプリケーションに Google+ iOS SDK を統合しました。
ユーザーがアカウントの詳細を入力したら、ユーザーをサインインしたままにしたい。

問題は、アプリケーションを終了して再度開くと、ユーザーがサインアウトし、ユーザーにサインインを求める必要があることです。

サインイン画面を表示する代わりに、アクセス トークンのようなものを保存して使用する方法はありますか? それとも、アプリケーションの終了時に Google 自体がユーザーをサインアウトしたためですか?

4

3 に答える 3

1

iOS 9、xcode 7.0.1 でのこの問題の解決策の現在のバージョンは、

(void) signInSilently   

GIDSignInオブジェクト参照で呼び出します。

Google が提供: 以前に認証されたユーザーを操作なしでサインインしようとします。 参照リンク

に応じて返されます

- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user
 withError:(NSError *)error{}

ユーザーが期限切れまたはログアウトした場合、 ( GIDGoogleUser *)userはnilになり、詳細は(NSError *)errorで表示され、ログインしているユーザーの場合はその逆になります。

それが誰かを助けることを願っています。

于 2015-11-18T12:06:29.963 に答える
1

私の場合、GPPSignInオブジェクトをグローバルにすることで問題が解決しました。 これ

を行う方法は次のとおりです。 folder-> file に、次の行を追加します。
Supporting Filesappname-Prefix.pch

#import <GooglePlus/GooglePlus.h>
GPPSignIn * signIn;

この行の下:

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
于 2013-06-03T09:08:22.963 に答える
0

Google+ ログイン用。ここでは、次のようにいくつかの手順があります

1.> まず、Google+ SDK を追加し、[API アクセス] ペインをクリックして Google プラス クライアント ID を作成します。

GoogleOpenSource.framework、* GooglePlus.bundle *、GooglePlus.frameworkを挿入

ClientID2.>そのようなマクロをグローバルに割り当てます

 #define kClientID  @"//paas client id which your app provided by developer account portal";

3.>AppDelegate.hファイルに実装する

#import <GooglePlus/GooglePlus.h>

extern NSString *const FBSessionStateChangedNotification;

@interface AppDelegate : UIResponder <UIApplicationDelegate,GPPDeepLinkDelegate>
{

}
-(void)clearApplicationCaches;

4.> 実装するAppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [GPPSignIn sharedInstance].clientID = kClientID;
    [GPPDeepLink setDelegate:self];
    [GPPDeepLink readDeepLinkAfterInstall];

    [self.window makeKeyAndVisible];
     return YES;
}
- (void)didReceiveDeepLink:(GPPDeepLink *)deepLink
{

}

#pragma mark - Memory management methods
-(void)clearApplicationCaches
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [self clearApplicationCaches];
}

- (BOOL)application: (UIApplication *)application openURL: (NSURL *)url sourceApplication: (NSString *)sourceApplication annotation: (id)annotation 
{
   return [GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation];
}

ヒント:この時点までテストしたい場合[signIn authenticate]は、メソッドの最後で呼び出すことができますviewDidLoad。アプリケーションは、起動時にサインイン ダイアログにリダイレクトします

5.> 次に、View Controller に移動し、yourViewController.hファイルに移動します

#import <GooglePlus/GooglePlus.h>

@class GPPSignInButton;

@interface yourViewController:UIViewController <GPPSignInDelegate>
{
}

@property(nonatomic, strong) IBOutlet GPPSignInButton *signInButton;

必要に応じてプロパティを合成しGPPSignInButtonますが、この手順は Xcode の新しいバージョンでは必要なくなりました。

@synthesize signInButton;

- (void)viewDidLoad
{
  [super viewDidLoad];
  [GPPSignInButton class];

  GPPSignIn *signIn = [GPPSignIn sharedInstance];
  signIn.clientID = kClientID;
  signIn.delegate = self;

  [signIn trySilentAuthentication]; /// this calls finishedWithAuth automatically
}

GPPSignInButtonをストーリーボード、XIB ファイルに追加するか、プログラムでインスタンス化します。GPPSignInButtonから継承するUIButtonため、ストーリーボードまたは XIB ファイルを使用している場合は、Round Rect Button または View をビュー コントローラーにドラッグし、そのカスタム クラスを に設定できますGPPSignInButton

ボタンをsignInButtonView Controllerのプロパティに接続します。

#pragma mark -
#pragma mark - GooglePluseDelegate Implementation

- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth error: (NSError *) error
{

    NSLog(@"email %@ ",[NSString stringWithFormat:@"Email: %@",[GPPSignIn sharedInstance].authentication.userEmail]);
    NSLog(@"Received error %@ and auth object %@",error, auth);

    // 1. Create a |GTLServicePlus| instance to send a request to Google+.
    GTLServicePlus* plusService = [[GTLServicePlus alloc] init] ;
    plusService.retryEnabled = YES;

    // 2. Set a valid |GTMOAuth2Authentication| object as the authorizer.
    [plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];


    GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:@"me"]; 

    // *4. Use the "v1" version of the Google+ API.*
    plusService.apiVersion = @"v1";


    [plusService executeQuery:query
            completionHandler:^(GTLServiceTicket *ticket,
                                GTLPlusPerson *person,
                                NSError *error) {
                if (error) {
                    GTMLoggerError(@"Error: %@", error);
                    [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
                    if (error) {
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil
                                                                  cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [alertView show];
                    }
                } else
                {
                    NSLog(@"userId = %@",query.activityId);

                    NSLog(@"person = %@",[person.name.familyName stringByAppendingFormat:@" %@",person.name.givenName]);

                    NSLog(@"person = %@", person);
                    NSDictionary *tempDic = [NSDictionary dictionaryWithObjectsAndKeys:[GPPSignIn sharedInstance].authentication.userEmail,@"email",person.identifier,@"googleID",[person.name.givenName stringByAppendingFormat:@" %@",person.name.familyName],@"name",[person.name.givenName stringByAppendingFormat:@" %@",person.name.familyName],@"username",person.gender,@"gender", nil];


               [NSThread detachNewThreadSelector:@selector(parsingLoginWithGoogleApi:) toTarget:self withObject:tempDic]; 
                }
            }];
}

// ---- its call a web service to login with google+ info
-(void) parsingLoginWithGoogleApi:(NSDictionary*) googleUserInfoDic
{

    NSLog(@"google User Info Dic = %@", googleUserInfoDic );
    NSString *name = @"";
    NSString *username = @"";
    NSString *emailId = @"";
    NSString *gender = @"";
    NSString *apiURLStr =@"";
    if ([DEFAULTS objectForKey:@"isLogin"])
    {
        name =[DEFAULTS objectForKey:@"g_name"];
        emailId =[DEFAULTS objectForKey:@"g_emailId"];
        username =[DEFAULTS objectForKey:@"g_username"];
        gender =[DEFAULTS objectForKey:@"g_gender"];


        apiURLStr =[NSString stringWithFormat:@"%@google_login/%@/%@/%@/%@",SiteAPIURL,emailId,[name stringByURLEncode],[username stringByURLEncode],gender];
    }
    else
    {
        name =[googleUserInfoDic valueForKey:@"name"];
        username =[googleUserInfoDic valueForKey:@"username"];
        emailId = @"0";
        if ([googleUserInfoDic valueForKey:@"email"])
            emailId=[googleUserInfoDic valueForKey:@"email"];

        gender = @"0";
        if ([googleUserInfoDic valueForKey:@"gender"])
            gender =[googleUserInfoDic valueForKey:@"gender"];

        apiURLStr =[NSString stringWithFormat:@"%@google_login/%@/%@/%@/%@",SiteAPIURL,emailId,[name stringByURLEncode],[username stringByURLEncode],gender];
    }

    NSLog(@"login Google apiURLStr==>>>%@",apiURLStr);

    NSString *outputStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiURLStr] encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"login Google response==>>>%@",outputStr);

    if (outputStr == NULL)
    {
        NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"There was a small problem",@"title",@"The network doesn't seem to be responding, please try again.",@"message",@"OK",@"cancel",@"1",@"tag",self,@"delegate", nil];
        [CommonFunctions performSelectorOnMainThread:@selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];

        [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
    }
    else
    {
        NSDictionary *jsonResponse = [outputStr JSONValue];

        if (jsonResponse != nil)
        {
            NSString *replycode=[jsonResponse objectForKey:@"replyCode"];

            if ([replycode isEqualToString:@"success"])
            {
                NSUserDefaults *userDefs = [NSUserDefaults standardUserDefaults];
                [userDefs setObject:name forKey:@"g_name"];
                [userDefs setObject:emailId forKey:@"g_emailId"];
                [userDefs setObject:username forKey:@"g_username"];
                [userDefs setObject:gender forKey:@"g_gender"];

                [userDefs setObject:[jsonResponse objectForKey:@"sesId"] forKey:@"sessionId"];
                sessionId = [jsonResponse objectForKey:@"sesId"];
                [userDefs setObject:username forKey:@"username"];
                [userDefs setObject:[jsonResponse objectForKey:@"userId"] forKey:@"userId"];
                [userDefs setObject:@"YES" forKey:@"isLogin"];
                [userDefs setObject:@"Google" forKey:@"LoginType"];
                userId = [jsonResponse objectForKey:@"userId"];
                [userDefs synchronize];

                [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
                [self performSelectorOnMainThread:@selector(pushProfileVC:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO];
            }
            else
            {
                [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];

                NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:replycode,@"title",[jsonResponse objectForKey:@"replyMsg"],@"message",@"OK",@"cancel",@"1",@"tag",nil,@"delegate", nil];
                [CommonFunctions performSelectorOnMainThread:@selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];
            }
        }
        else
        {
            [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];

            NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"There was a small problem",@"title",@"The network doesn't seem to be responding, please try again.",@"message",@"OK",@"cancel",@"1",@"tag",self,@"delegate", nil];
            [CommonFunctions performSelectorOnMainThread:@selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];
        }
    }

}

お役に立てば幸いです。ありがとう

于 2013-05-27T14:12:03.990 に答える