I am new to game centre and I am building multiplayer game. I have different users in my tableview; now I want to send an invite for a match to a specific user. For sending the invitation I am using this code:
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = 2;
request.maxPlayers = 2;
request.playersToInvite = [[NSArray alloc] initWithObjects:player.playerId, nil];
request.inviteMessage = #"Your Custom Invitation Message Here";
request.inviteeResponseHandler = ^(NSString *playerID, GKInviteeResponse response)
{
[self updateUIForPlayer: playerID accepted: (response == GKInviteeResponseAccepted)];
};
But how to receive that invitation? I think I have to implement a method for this in GameKitHelper class but I am not sure how to handle this.
my teacher helped me with this and i thought to post working code here if anyone stuck here can use this code.
- (void)inviteFriends: (NSArray*) friends
{
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = 2;
request.maxPlayers = 2;
request.defaultNumberOfPlayers = 2;
request.recipients = friends;
request.inviteMessage = #"Your Custom Invitation Message Here";
[[GKMatchmaker sharedMatchmaker] findMatchForRequest:request withCompletionHandler:^(GKMatch* match, NSError *error) {
if (error)
{
//Invite has not been sent
// //NSLog(#"Invitation has not been sent");
}
else if (match != nil)
{
//whatever you want to do when the receiver accepts the invite
//NSLog(#"Invitation has been sent with match object = %#",match);
}
}];
request.recipientResponseHandler= ^(GKPlayer *player, GKInviteeResponse response)
{
//NSLog(#"response Get From Other User.");
switch (response) {
case GKInviteeResponseAccepted:
{
}
break;
case GKInviteeResponseDeclined:
{
}
break;
case GKInviteeResponseFailed:
{
}
break;
case GKInviteeResponseIncompatible:
{
}
break;
case GKInviteeResponseUnableToConnect:
{
}
break;
case GKInviteeResponseNoAnswer:
{
}
break;
default:
break;
}
};
}
Related
I am trying to acquire token Interactively for multiple scopes, Policy and RMS scopes using Objective C. I am not sure whether I am doing it right or wrong, the way I am trying to get it as below.
I have written a method "aquireToken" where I am calling the function twice one for Policy scope and other RMS scope and updating result in NSDictionary.
There is a flag which is being updated inside the "completionBlock = ^(MSALResult *result, NSError *error)". But its value is not reflected in the caller "aquireToken" function.
The code snippet is as below:
- (void) aquireToken
{
policyTokenResult = false;
rmsTokenResult = false;
NSError *error = nil;
MSALPublicClientApplication *application = [self createPublicClientApplication:&error];
[self retrieveTokens:application forScopes:scopesPolicy isPolicy:true];
if (policyTokenResult)
{
[self retrieveTokens:application forScopes:scopesRMS isPolicy:false];
}
for (NSString* key in resultMap) {
id value = resultMap[key];
// id object = [resultDict objectForKey:key];
NSLog(#"%# = %#", key, value);
// do stuff
}
}
- (void)retrieveTokens:(MSALPublicClientApplication*) application
forScopes: (NSArray<NSString *> *) scopes
isPolicy: (BOOL) isPolicy
{
NSError *error = nil;
MSALAccount* userAccount = nil;
for (MSALAccount *account in [application allAccounts:&error])
{
if([[account.username uppercaseString] isEqualToString:[authID uppercaseString]])
{
NSLog(#"Account Found: \t%#", account.username);
userAccount = account;
break;
}
}
MSALCompletionBlock completionBlock;
__block __weak MSALCompletionBlock weakCompletionBlock;
weakCompletionBlock = completionBlock = ^(MSALResult *result, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^{
if (!error)
{
if (isPolicy)
{
[resultMap setObject:result.accessToken forKey:#"PolicyAccessToken"];
[resultMap setObject:result.account.username forKey:#"UserId"];
authID = result.account.username;
policyTokenResult = true;
}
else
{
[resultMap setObject:result.accessToken forKey:#"RMSAccessToken"];
rmsTokenResult = true;
}
if(policyTokenResult && rmsTokenResult)
{
[resultMap setObject:#"" forKey:#"ResultStatusSuccess"];
}
return;
}
if ([error.domain isEqualToString:MSALErrorDomain] && error.code == MSALErrorInteractionRequired)
{
[self acquireTokenInteractive:application scopes:scopes isPolicy:isPolicy completionBlock:weakCompletionBlock];
return;
}
});
};
if(userAccount)
{
[self acquireTokenSilent:application scopes:scopes forAccount:userAccount isPolicy:isPolicy completionBlock:completionBlock];
}
else
{
[self acquireTokenInteractive:application scopes:scopes isPolicy:isPolicy completionBlock:completionBlock];
}
}
- (void) acquireTokenSilent: (MSALPublicClientApplication *) application
scopes: (NSArray<NSString *> *) scopes
forAccount: (MSALAccount *) userAccount
isPolicy: (BOOL) isPolicy
completionBlock: (MSALCompletionBlock) completionBlock
{
MSALSilentTokenParameters *silentParams = [[MSALSilentTokenParameters alloc] initWithScopes:scopes account:userAccount];
[application acquireTokenSilentWithParameters:silentParams completionBlock:completionBlock];
}
- (void) acquireTokenInteractive: (MSALPublicClientApplication *) application
scopes: (NSArray<NSString *> *) scopes
isPolicy: (BOOL) isPolicy
completionBlock: (MSALCompletionBlock)completionBlock
{
MSALInteractiveTokenParameters *interactiveParams = [[MSALInteractiveTokenParameters alloc] initWithScopes:scopes];
[interactiveParams setPromptType:MSALPromptTypeSelectAccount];
interactiveParams.completionBlockQueue = dispatch_get_main_queue();
[application acquireTokenWithParameters:interactiveParams completionBlock:completionBlock];
}
I want to use TouchID authenticate my own app.
1.I want user can click 'Enter passcode' to invoke system build-in passcode screen to authenticate,if success then enter my own app.
But I don't how know to make it forward to passcode authenticate view like the following screen in 'case LAErrorUserFallback'
Here is my code :
LAContext *context = [[LAContext alloc] init];
__block NSString *msg;
__block BOOL bAuth;
// show the authentication UI with our reason string
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(#"Unlock APP With FingerPrint", nil) reply:
^(BOOL success, NSError *authenticationError) {
if (success) {
bAuth = YES;
msg =[NSString stringWithFormat:NSLocalizedString(#"EVALUATE_POLICY_SUCCESS", nil)];
dispatch_async(dispatch_get_main_queue(), ^{
[[MYAppDelegate theDelegate] initializeAppAfterKeyVaultUnlocked];
});
NSLog(#"%#",msg);
} else {
bAuth = NO;
switch (authenticationError.code) {
case LAErrorAuthenticationFailed:
msg = [NSString stringWithFormat:NSLocalizedString(#"Authentication Failed", nil)];
// ...
break;
case LAErrorUserCancel:
msg = [NSString stringWithFormat:NSLocalizedString(#"User pressed Cancel button", nil)];
dispatch_async(dispatch_get_main_queue(), ^{
[[MYAppDelegate theDelegate] exitAndLock];
});
break;
case LAErrorUserFallback:
msg = [NSString stringWithFormat:NSLocalizedString(#"User pressed \"Enter Password\"", nil)];
//Here I want to fallback to iOS build-in passcode authenticate view, and get the auth result.
break;
default:
msg = [NSString stringWithFormat:NSLocalizedString(#"Touch ID is not configured", nil)];
// ...
break;
}
NSLog(#"%#",authenticationError.localizedDescription);
}
}];
Now in iOS 9 it is pretty simple actually - you just have to use LAPolicyDeviceOwnerAuthentication instead of LAPolicyDeviceOwnerAuthenticationWithBiometrics
So in your code you just replace this:
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(#"Unlock APP With FingerPrint", nil) reply:
^(BOOL success, NSError *authenticationError) {
With this:
[context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:NSLocalizedString(#"Unlock APP With FingerPrint", nil) reply:
^(BOOL success, NSError *authenticationError) {
Thus, when user fails to authenticate with fingerprint, there'd be "enter passcode" option which would invoke system passcode input screen.
In my understanding, you will have to build the passcode screen yourself if you want to use evaluatePolicy.
If you use keychain, the SecItemCopyMatching function automatically falls back to passcode if fingering fails. Here's a reference on how to get it going (see section 3): https://www.secsign.com/fingerprint-validation-as-an-alternative-to-passcodes/
Didn't try that, but this post claim you can use the system as follow here (This works only with iOS 8 or later).
Or (which is what I did) you can build your passcode entry screen (to support older iOS versions), my controller have a passcode entry view, which will get exposed when the user select use passcode. At that point the call back from evaluatePolicy will return with LAErrorUserFallback, which can be the time to open your custom passcode screen.
something like that:
-(void)maybeShowTouchIDMessage {
if (![SettingsManager sharedManager].isUseTouchID || self.createPassCodeMode) {
self.shieldView.hidden = YES;
return;
}
self.shieldView.hidden = NO;
self.shieldView.alpha = 1.0;
LAContext *context = [[LAContext alloc] init];
NSError *evalError = nil;
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&evalError] ) {
__weak SecurityWindowViewController *weakSelf = self;
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:#"Use touch id \n or hit \"Cancel\" to enter passcode"
reply:^(BOOL success, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
SecurityWindowViewController *strongSelf = weakSelf;
if (success) {
[strongSelf hideWithSuccess:YES];
} else if (error){
NSString *errorMessage;
BOOL showError = NO;
switch (error.code) {
case LAErrorAuthenticationFailed:
errorMessage = #"Sorry couldn't autheticate";
showError = YES;
break;
case LAErrorPasscodeNotSet:
errorMessage = #"Sorry couldn't autheticate";
showError = YES;
break;
case LAErrorTouchIDNotEnrolled:
errorMessage = #"Touch ID has no enrolled fingers";
showError = YES;
break;
default:
showError = NO;
break;
}
[UIView animateWithDuration:0.5 animations:^{
strongSelf.shieldView.alpha = 0.0;
} completion:^(BOOL finished) {
strongSelf.shieldView.hidden = YES;
}];
if (showError) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:errorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
}
});
}];
}
For your case :
case LAErrorUserFallback:
[context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:NSLocalizedString(#"Unlock APP With PassCode", nil) reply: ^(BOOL success, NSError *authenticationError) {
if(success){
NSLog(#"PassCode Login successful");
}else{
NSLog(#"%#",authenticationError);
}
}
For device passcode verification you need to use LAPolicyDeviceOwnerAuthentication instead of LAPolicyDeviceOwnerAuthenticationWithBiometrics. Hope this helps !!
You can add another case and call your passcode screen from that.
Here is my code:
LAContext *myContext = [[LAContext alloc] init];
NSError *authError = nil;
NSString *myLocalizedReasonString = strMessage;
objFlockr.pVerificationBlock = objResponse;
if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
if (!isShow) {
myContext.localizedFallbackTitle = #"";
}
else
{
myContext.localizedFallbackTitle = #"Set Up Passcode";
}
[myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:myLocalizedReasonString
reply:^(BOOL succes, NSError *error) {
if (!AppDel.firstAttampt && succes && !isShow)
{
if (objFlockr.pVerificationBlock)
objFlockr.pVerificationBlock(1);
}
else if (succes) {
if (objFlockr.pVerificationBlock)
objFlockr.pVerificationBlock(0);
NSLog(#"User authenticated");
} else {
switch (error.code) {
case LAErrorAuthenticationFailed:
NSLog(#"Authentication Failed");
if (objFlockr.pVerificationBlock)
objFlockr.pVerificationBlock(1);
break;
case LAErrorUserCancel:
NSLog(#"User pressed Cancel button");
if (objFlockr.pVerificationBlock)
objFlockr.pVerificationBlock(3);
break;
case LAErrorUserFallback:
NSLog(#"User pressed \"Enter Password\"");
if (objFlockr.pVerificationBlock)
objFlockr.pVerificationBlock(4);
break;
default:
[self showMessage:#"Touch ID is not configured" withTitle:#"Error"];
if (objFlockr.pVerificationBlock)
objFlockr.pVerificationBlock(2);
NSLog(#"Touch ID is not configured");
break;
}
NSLog(#"Authentication Fails");
}
}];
} else {
NSLog(#"Can not evaluate Touch ID");
[self showMessage:#"Can not evaluate TouchID" withTitle:#"Error"];
}
Replace LAPolicy policy enum value deviceOwnerAuthenticationWithBiometrics with deviceOwnerAuthentication
Note: If user has enable biometric (face id or touch id) authentication, then device will ask first for biometric authentication and if user choose fall back authentication, then only deviceOwnerAuthentication will show passcode screen.
Try this and see (swift 4):
func touchIDAuthentication() {
let context = LAContext()
var error:NSError?
// edit line - deviceOwnerAuthentication
guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
//showAlertViewIfNoBiometricSensorHasBeenDetected()
return
}
// edit line - deviceOwnerAuthentication
if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &errorPointer) {
// edit line - deviceOwnerAuthentication
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason, reply: { (success, error) in
if success {
DispatchQueue.main.async {
print("Authentication was successful")
}
}else {
DispatchQueue.main.async {
//self.displayErrorMessage(error: error as! LAError )
print("Authentication was error")
}
}
})
}else {
// self.showAlertWith(title: "Error", message: (errorPointer?.localizedDescription)!)
}
}
When I create an event:
EKEvent *newEvent = [EKEvent eventWithEventStore:self.store];
newEvent.title = title;
newEvent.startDate = startDate;
newEvent.endDate = finishDate;
newEvent.location = location;
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:hoursOffSet * 60 * 60];
[newEvent addAlarm:alarm];
newEvent.calendar = cal;
BOOL eventSaved = [self.store saveEvent:newEvent span:EKSpanFutureEvents commit:YES error:error];
NSLog(#"identifier %#",newEvent.eventIdentifier);
if (!eventSaved) {
if(!cal)
{
*error = [NSError errorWithDomain:#"ASTEventStore" code:CALENDAR_NOT_FOUND_CODE_ERROR userInfo:NULL];
}
NSLog(#"Event didn't save in calendar %#",errorSavingInCalendar);
}
It usually works right, but I have discovered that sometimes it's saving the event and it doesn't get any error, but I can't see the event in the calendar App, actually I can't see the calendar created neither.
When I save the event in the device I always get its id in the Organizer-> Console in this way:
: identifier /The same id than the newEvent.eventIdentifier/
Do you know what does that warning means?
////Update
Well, I noticed that when the app save the EKEvent and the warning message is shown, another message is shown too:
: 2014-08-12 10:32:28.153|17|0x178e6d500: Region monitoring not available or enabled. Trigger ignored!
I tried too google it, but I didn't find out anything.
Any ideas?
Thanks :)
Well I think I found the solution, the problem was when I was creating the calendar I was getting the source in a wrong way: (from: how do I create a new EKCalendar on iOS device?)
// find local source for example
EKSource *localSource = nil;
for (EKSource *source in self.store.sources)
{
if (source.sourceType == EKSourceTypeLocal) // or another source type that supports
{
localSource = source;
break;
}
}
if (!localSource) {
NSLog(#"Local source is not available");
if (error) {
*error = [NSError errorWithDomain:#"ASTEventStore" code:CALENDAR_ACCOUNT_NOT_TYPE_LOCAL userInfo:NULL];
}
}
else{
cal = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.store];
cal.title = #"Calendar";
cal.source = self.store.defaultCalendarForNewEvents.source;
cal.CGColor = [UIColor blueColor].CGColor;
NSError *calendarError;
BOOL calendarSaved = [self.store saveCalendar:cal commit:YES error:&calendarError];
if (!calendarSaved) {
NSLog(#"calendar didn't saved %#",calendarError);
}
NSLog(#"cal id = %#", cal.calendarIdentifier);
//We save the calendar ID
calendarId = cal.calendarIdentifier;
[defaults setObject:calendarId forKey:#"calendarId"];
BOOL saved = [defaults synchronize];
if (!saved) {
NSLog(#"CALENDAR_ID didn't saved");
}
}
Now I getting from defaultCalendarForNewEvents:
cal = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.store];
cal.title = #"Calendar";
cal.source = self.store.defaultCalendarForNewEvents.source;
cal.CGColor = [UIColor blueColor].CGColor;
NSError *calendarError;
BOOL calendarSaved = [self.store saveCalendar:cal commit:YES error:&calendarError];
if (!calendarSaved) {
NSLog(#"calendar didn't saved %#",calendarError);
}
NSLog(#"cal id = %#", cal.calendarIdentifier);
if (!saved) {
NSLog(#"CALENDAR_ID didn't saved");
}
I tested and it's working great in iOS7.
I hope this help to someone :)
<\RESOLVED>, Please see the first reply
My mac(10.9) has joined into a AD domain. In my program, I tried to recognize whether the current login user is local account or AD user. I can successfully distinguish them by using the following code.
+ (bool)isLocalUser:(NSString*)user
{
NSError *dirSearchError = nil;
ODRecord *foundUser = findUser(user, &dirSearchError);
if(foundUser !=nil)
{
return YES;
}else
{
return NO;
}
}
ODRecord *findUser(NSString *user, NSError **error)
{
NSLog(#"[MacLogonUI] findUser");
ODNode *searchNode = [ODNode nodeWithSession: [ODSession defaultSession]
type: kODNodeTypeLocalNodes
error: error];
if (searchNode == nil) {
return nil;
}
NSDictionary *nodeInfo = [searchNode nodeDetailsForKeys:nil error:error];
/* query this node for the user record we're interested in.
* We only need one result, which is why maximumResults is set to 1.
*/
ODQuery *userSearch = [ODQuery queryWithNode: searchNode
forRecordTypes: kODRecordTypeUsers
attribute: kODAttributeTypeRecordName
matchType: kODMatchEqualTo
queryValues: user
returnAttributes: kODAttributeTypeStandardOnly
maximumResults: 1
error: error];
if (userSearch == nil) {
return nil;
}
/* For this example we'll use a synchronous search. This could take a while
* so asynchronous searching is preferable.
*/
NSArray *foundRecords = [userSearch resultsAllowingPartial: NO error: error];
if (foundRecords == nil || [foundRecords count] == 0) {
return nil;
}
ODRecord *userRecord = [foundRecords objectAtIndex: 0];
return [[userRecord retain] autorelease];
}
While when the AD user create a mobile card, it is viewed as a managed user(from the System preference -> Users & Groups). The code also recognize this kind of AD user as local. How to deal with this kind of situation?
Do you guys have any idea of this problem?
I have solved this problem by myself. Hope the following code helps:
#import "DasUser.h"
#import <OpenDirectory/OpenDirectory.h>
#import <Collaboration/Collaboration.h>
#implementation DasUser
+ (bool)isLocalUser:(NSString*)user
{
NSError *dirSearchError = nil;
ODRecord *foundUser = findUser(user, &dirSearchError);
if(foundUser !=nil)
{
return YES;
}else
{
return NO;
}
}
ODRecord *findUser(NSString *user, NSError **error)
{
NSLog(#"[MacLogonUI] findUser");
CSIdentityAuthorityRef defaultAuthority = CSGetManagedIdentityAuthority();
CSIdentityClass identityClass = kCSIdentityClassUser;
CSIdentityQueryRef query = CSIdentityQueryCreate(NULL, identityClass, defaultAuthority);
CFErrorRef err = NULL;
CSIdentityQueryExecute(query, 0, &err);
CFArrayRef results = CSIdentityQueryCopyResults(query);
int numResults = CFArrayGetCount(results);
NSMutableArray * managedUsers = [NSMutableArray array];
for (int i = 0; i < numResults; ++i) {
CSIdentityRef identity = (CSIdentityRef)CFArrayGetValueAtIndex(results, i);
CBIdentity * identityObject = [CBIdentity identityWithCSIdentity:identity];
NSString* posixName = [identityObject posixName];
[managedUsers addObject:posixName];
}
CFRelease(results);
CFRelease(query);
ODNode *searchNode = [ODNode nodeWithSession: [ODSession defaultSession]
type: kODNodeTypeLocalNodes
error: error];
if (searchNode == nil) {
return nil;
}
/* query this node for the user record we're interested in.
* We only need one result, which is why maximumResults is set to 1.
*/
ODQuery *userSearch = [ODQuery queryWithNode: searchNode
forRecordTypes: kODRecordTypeUsers
attribute: kODAttributeTypeRecordName
matchType: kODMatchEqualTo
queryValues: user
returnAttributes: kODAttributeTypeStandardOnly
maximumResults: 1
error: error];
if (userSearch == nil) {
return nil;
}
/* For this example we'll use a synchronous search. This could take a while
* so asynchronous searching is preferable.
*/
NSArray *foundRecords = [userSearch resultsAllowingPartial: NO error: error];
if([foundRecords count]>0)
{
NSString *nameStr = [foundRecords[0] recordName];
NSLog(#"[MacLogonUI] findUser nameStr %#", nameStr);
int j;
for( j = 0; j<[managedUsers count]; j++)
{
if([nameStr isEqualToString:managedUsers[j]])
{
break;
}
}
if(j<[managedUsers count])
{
foundRecords = nil;
}
}
if (foundRecords == nil || [foundRecords count] == 0) {
return nil;
}
ODRecord *userRecord = [foundRecords objectAtIndex: 0];
return [[userRecord retain] autorelease];
}
#end
While when network of the mac is disconnected. The managed user can not be listed. Is there anybody has any idea of this?
Currently playing around with GooglePlusSample with scope:
#"https://www.googleapis.com/auth/plus.me",
#"https://www.googleapis.com/auth/userinfo.email" and
#"https://www.googleapis.com/auth/userinfo.profile".
Tried calling auth.userEmail, auth.userData in callback method finishedWithAuth:error:, but both are empty...
-(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error{
NSLog(#"Received Error %# and auth object==%#",error,auth);
if (error) {
// Do some error handling here.
} else {
[self refreshInterfaceBasedOnSignIn];
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) {
//Handle Error
} else
{
NSLog(#"Email= %#",[GPPSignIn sharedInstance].authentication.userEmail);
NSLog(#"GoogleID=%#",person.identifier);
NSLog(#"User Name=%#",[person.name.givenName stringByAppendingFormat:#" %#",person.name.familyName]);
NSLog(#"Gender=%#",person.gender);
}
}];
}
}
Once user is authenticated you can call [[GPPSignIn sharedInstance] userEmail] to get authenticated user's email.
This worked for me :
Firstly use the userinfo.email scope as per :
signInButton.scope = [NSArray arrayWithObjects:
kGTLAuthScopePlusMe,
kGTLAuthScopePlusUserinfoEmail,
nil];
Then define these methods :
- (GTLServicePlus *)plusService {
static GTLServicePlus* service = nil;
if (!service) {
service = [[GTLServicePlus alloc] init];
// Have the service object set tickets to retry temporary error conditions
// automatically
service.retryEnabled = YES;
// Have the service object set tickets to automatically fetch additional
// pages of feeds when the feed's maxResult value is less than the number
// of items in the feed
service.shouldFetchNextPages = YES;
}
return service;
}
- (void)fetchUserProfile {
// Make a batch for fetching both the user's profile and the activity feed
GTLQueryPlus *profileQuery = [GTLQueryPlus queryForPeopleGetWithUserId:#"me"];
profileQuery.fields = #"id,emails,image,name,displayName";
profileQuery.completionBlock = ^(GTLServiceTicket *ticket, id object, NSError *error) {
if (error == nil) {
// Get the user profile
GTLPlusPerson *userProfile = object;
// Get what we want
NSArray * userEmails = userProfile.emails;
NSString * email = ((GTLPlusPersonEmailsItem *)[userEmails objectAtIndex:0]).value;
NSString * name = userProfile.displayName;
NSString * profileId = userProfile.identifier;
} else {
// Log the error
NSLog(#"Error : %#", [error localizedDescription]);
}
};
GTLBatchQuery *batchQuery = [GTLBatchQuery batchQuery];
[batchQuery addQuery:profileQuery];
GTLServicePlus *service = self.plusService;
self.profileTicket = [service executeQuery:batchQuery
completionHandler:^(GTLServiceTicket *ticket,
id result, NSError *error) {
self.profileTicket = nil;
// Update profile
}];
}
And finally call the "fetchUserProfile" method in the "finishedWithAuth" as per :
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
error: (NSError *) error
{
// An error?
if (error != nil) {
// Log
} else {
// Set auth into the app delegate
myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.auth = auth;
// Get user profile
self.plusService.authorizer = auth;
[self fetchUserProfile];
}
}
Note this may not be perfect as it's a 'work in progress', in particular re: getting the correct email address when the user has more than one but it's a start!
Good luck.
Steve
If you have Access not configured error check services in google api console. make sure you enable google plus api services.