Google plus sign-in for xcode share extension

2019-05-16 00:07发布

问题:

I’m writing an iOS app to share web page links by email, and as part of it I want users to be able to sign in to google plus. I’ve got the containing app working fine using the instructions from here:

https://developers.google.com/+/mobile/ios/sign-in

and now I’m trying to add a share extension that can also access the user’s google+ profile. I started off by trying to add the sign in button in to the share extension, but I don’t think that’s going to work because after clicking the button you’re taken out of the app to the browser to accept permissions, and then there’s no way to redirect back to the share extension (or at least I can’t see a way).

What I’m hoping now is that it’s possible for the user to sign in and accept permissions in the main (containing) app, but to then later use the share extension, and still be signed in with the same profile. I’m using a custom UIViewController in the share extension, and as a first attempt I’ve tried to use the same client id in the share extension as the containing app and to call this in the viewDidLoad method:

GPPSignIn *signIn = [GPPSignIn sharedInstance];
signIn.shouldFetchGooglePlusUser = YES;
signIn.shouldFetchGoogleUserEmail = YES;
signIn.clientID = kClientID;
signIn.scopes = @[ @"profile" ];
signIn.delegate = self;
if ([signIn hasAuthInKeychain]) {
    NSLog(@"Has auth in keychain");
} else {
    NSLog(@"No auth in keychain");
}

in the containing app hasAuthInKeychain returns true, but in the share extension it’s false. The client id that I’m using is tied to the bundle for main app, so I’m not sure if I should be able to use it in the share extension anyway, but if I tried to create a separate client id for the share extension then presumably I’d need to go through the authorisation process again?

Is there a way that I can get access to the existing auth token from the main app and use it in the share extension?

回答1:

You're on the right track.

To access the same keychain in both the app and the extension, you need to enable the "Keychain Sharing" capability for both of them in Xcode. When you do this, Xcode will probably want to update your app ID and provisioning profiles, because they need to reflect the new capability.

Whether this is enough depends on how the Google framework handles the keychain, though. It's probably all you need, because as the docs for SecItemAdd indicate, items will be added to the first listed group by default. But I don't know how Google's code works so I can't be certain of that.

Once you do this, you'll probably have to reauthorize the app to get the credentials into the right group. After that though, both app and extension can look up existing values.