how to get UserID from Google plus Oauth2.0 for IOS - ios

I used Google Developers Documentation but I can't take UserID
this is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.0f/255.0f green:102.0f/255.0f blue:204.0f/255.0f alpha:100.0];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
signIn = [GPPSignIn sharedInstance];
// You previously set kClientId in the "Initialize the Google+ client" step
signIn.clientID = kClientId;
[signIn setScopes:[NSArray arrayWithObject: #"https://www.googleapis.com/auth/plus.me"]];
// Uncomment to get the user's email
signIn.shouldFetchGoogleUserEmail = YES;
// Uncomment to get the user's ID
signIn.shouldFetchGoogleUserID = YES;
signIn.delegate = self;
Gplusbtn = [[GPPSignInButton alloc] init];
Gplusbtn.frame = CGRectMake([simod CG:10], [simod CG:125], [simod CG:300], [simod CG:30]);
Gplusbtn.style=kGPPSignInButtonStyleWide;
Gplusbtn.enabled = YES;
[self.view addSubview:Gplusbtn];
}
- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error) {
_signInAuthStatus.text =
[NSString stringWithFormat:#"Status: Authentication error: %#", error];
return;
}
NSLog(#"ID:%#", signIn.userID);
}
NSLog show ID:(null)
So where code has a problem, how to fix it?

You just need to use
[GPPSignIn sharedInstance]
like this:
NSString * gpUserID = [GPPSignIn sharedInstance].userID;

Related

Google Plus Sign in From other UIViewController

when i signin in the Main ViewController in my Case ViewController.m every think works fine
with same code i sign in on other UIViewController login.m
when i close the app and run again trysilentauthentication will return false always
its lookalike nothing saved
i use this code to sign in login.m :
signIn = [GPPSignIn sharedInstance];
signIn.shouldFetchGooglePlusUser = YES;
signIn.shouldFetchGoogleUserEmail = YES;
signIn.clientID = kClientId;
signIn.scopes = #[ kGTLAuthScopePlusLogin ];
signIn.delegate = self;
[signIn authenticate];
and i check in ViewController.m :
if ([signIn trySilentAuthentication]) {
NSLog(#"trySilentAuthentication Return True");
}else {
NSLog(#"trySilentAuthentication Return False");
}
and i sign out in login.m using :
- (IBAction)signOut:(id)sender {
[self ClearUserData];
[[GPPSignIn sharedInstance] signOut];
[self refreshInterfaceBasedOnSignIn];
}
is it something With Delegate ?

User must be signed in to use the native share box

I want to add share on google-plus property in my application.
I registered client application on google web console and obtained client-id.
In my viewDidLoad function :
- (void)viewDidLoad{
CGRect rect = self.view.bounds;
rect.size.height = rect.size.height - 50;
_postContentUIWV = [[UIWebView alloc] initWithFrame:rect];
[_postContentUIWV loadHTMLString:selectedPostCD.content baseURL:nil];
[self.view addSubview:_postContentUIWV];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
GPPSignIn *signIn = [GPPSignIn sharedInstance];
signIn.shouldFetchGooglePlusUser = YES;
// signIn.shouldFetchGoogleUserEmail = YES; // Uncomment to get the user's email
// You previously set kClientId in the "Initialize the Google+ client" step
signIn.clientID = kClientID;
[GPPSignIn sharedInstance].actions = [NSArray arrayWithObjects:
#"http://schemas.google.com/AddActivity",
#"http://schemas.google.com/BuyActivity",
#"http://schemas.google.com/CheckInActivity",
#"http://schemas.google.com/CommentActivity",
#"http://schemas.google.com/CreateActivity",
#"http://schemas.google.com/ListenActivity",
#"http://schemas.google.com/ReserveActivity",
#"http://schemas.google.com/ReviewActivity",
nil];
// Uncomment one of these two statements for the scope you chose in the previous step
signIn.scopes = #[ kGTLAuthScopePlusLogin ]; // "https://www.googleapis.com/auth/plus.login" scope
//signIn.scopes = #[ #"profile" ]; // "profile" scope
// Optional: declare signIn.actions, see "app activities"
signIn.delegate = self;
[signIn trySilentAuthentication];
}
Then in my onButtonCLick function:
- (void) googlePlusShareTapped {
id<GPPNativeShareBuilder> shareBuilder = [[GPPShare sharedInstance] nativeShareDialog];
[shareBuilder setURLToShare:[NSURL URLWithString:#"https://www.shinnxstudios.com"]];
[shareBuilder setPrefillText:#"This is an awesome G+ Sample to share"];
// [shareBuilder setTitle:#"Title" description:#"Descp" thumbnailURL:[NSURL URLWithString:#"https://www.fbo.com/imageurl"]];
[shareBuilder open];
}
However I get the message:
[lvl=3] -[GPPNativeShareBuilderImpl open] User must be signed in to use the native share box.
I downloaded google+ app from App Store and signed in. But every time I get this message and cannot share anything on google+.
Any suggestions?
First remove your application from simulator then close XCode and reopen and run your app again by changing with following code:
GPPSignIn *signIn = [GPPSignIn sharedInstance];
signIn.shouldFetchGooglePlusUser = YES;
signIn.clientID = kClientId;
signIn.scopes = #[ kGTLAuthScopePlusLogin ];
signIn.delegate = self;
[signIn authenticate];
And also make sure that you have to added GooglePlus.bundle in to your application.

How to Configure XMPP Facebook chat in iOS application

I am developing an iOS application which uses the Facebook chat feature.
(I am using the XMPPFramework by Robbie Hanson).
https://github.com/robbiehanson/XMPPFramework
In connect method i have given my user name and password
- (BOOL)connect
{
if (![xmppStream isDisconnected]) {
return YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
//
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
myJID = #"example#facebook.com";
myPassword = #"Mypassword";
if (myJID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
in up stream method i have given my host name and port number
- (void)setupStream
{
NSAssert(xmppStream == nil, #"Method setupStream invoked multiple times");
xmppStream = [[XMPPStream alloc] init];
#if !TARGET_IPHONE_SIMULATOR
{
xmppStream.enableBackgroundingOnSocket = YES;
}
#endif
xmppReconnect = [[XMPPReconnect alloc] init];
xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];
xmppRoster.autoFetchRoster = YES;
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:xmppvCardStorage];
xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:xmppvCardTempModule];
xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:xmppCapabilitiesStorage];
xmppCapabilities.autoFetchHashedCapabilities = YES;
xmppCapabilities.autoFetchNonHashedCapabilities = NO;
// Activate xmpp modules
[xmppReconnect activate:xmppStream];
[xmppRoster activate:xmppStream];
[xmppvCardTempModule activate:xmppStream];
[xmppvCardAvatarModule activate:xmppStream];
[xmppCapabilities activate:xmppStream];
// Add ourself as a delegate to anything we may be interested in
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppStream setHostName:#"chat.facebook.com"];
[xmppStream setHostPort:5222];
// You may need to alter these settings depending on the server you're connecting to
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = NO;
}
Is there any steps that I have missed out? I have no idea how to proceed further. Help me if any one know the solution. Please help me out
Thanks in advance.
Try securing the connection using:
[xmppStream secureConnection:(NSError *)];
in the
- (void)xmppStreamDidConnect:(XMPPStream *)sender;
delegate method.
Hope it helps.

Second device doesn't get video call

I'm using QuickBlox to make a video call from one device to the other.
This is my code on the device making the call:
On viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.videoChat = [[QBChat instance] createAndRegisterVideoChatInstance];
self.videoChat.viewToRenderOpponentVideoStream = self.otherUserView;
self.videoChat.viewToRenderOwnVideoStream = self.selfView;
QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
extendedAuthRequest.userLogin = USERNAME
extendedAuthRequest.userPassword = PASSWORD
[QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
}
Session created
#pragma mark - QBActionStatusDelegate
- (void)completedWithResult:(Result *)result{
if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){
// Success, You have got User session
QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;
QBUUser *currentUser = [QBUUser user];
currentUser.ID = res.session.userID;
currentUser.password = PASSWORD
// set Chat delegate
[QBChat instance].delegate = self;
// login to Chat
[[QBChat instance] loginWithUser:currentUser];
}
}
Logged in to chat
(void) chatDidLogin {
// You have successfully signed in to QuickBlox Chat
[NSTimer scheduledTimerWithTimeInterval:30 target:[QBChat instance] selector:#selector(sendPresence) userInfo:nil repeats:YES];
}
Making the call:
- (IBAction)callUser:(id)sender {
[QBChat instance].delegate = self;
[self.videoChat callUser:USERID conferenceType:QBVideoChatConferenceTypeAudioAndVideo];
}
Getting the call
I've checked. The user is logged into the chat, the ID I'm trying to call is correct and the other user is also logged into the chat, but this never gets called:
-(void) chatDidReceiveCallRequestFromUser:(NSUInteger)userID withSessionID:(NSString *)_sessionID conferenceType:(enum QBVideoChatConferenceType)conferenceType {
self.videoChat = [[QBChat instance] createAndRegisterVideoChatInstanceWithSessionID:_sessionID];
//
[self.videoChat acceptCallWithOpponentID:userID conferenceType:conferenceType];
}
So Here is the answer, I was creating the QBVideoChat object too early. I ended up creating it after I'm logged into the chat
-(void) chatDidLogin {
// You have successfully signed in to QuickBlox Chat
[NSTimer scheduledTimerWithTimeInterval:30 target:[QBChat instance] selector:#selector(sendPresence) userInfo:nil repeats:YES];
self.videoChat = [[QBChat instance] createAndRegisterVideoChatInstance];
self.videoChat.viewToRenderOpponentVideoStream = self.otherUserView;
self.videoChat.viewToRenderOwnVideoStream = self.selfView;
}

Google Plus api for iOS get friend list

I want to get friends(People) list from Google+ in iOS app.
I am using Google+ api tutorial given in link
https://developers.google.com/+/mobile/ios/getting-started
I am created new project on Google+ Developer Console the link is
https://console.developers.google.com/project
Getting following error in -(void)getPeopleInfo.
[lvl=3] __31-[ViewController getPeopleInfo]_block_invoke() Error: Error Domain=com.google.GTLJSONRPCErrorDomain Code=401 "The operation couldn’t be completed. (Invalid Credentials)" UserInfo=0x14d89340 {error=Invalid Credentials, GTLStructuredError=GTLErrorObject 0x14d855e0: {message:"Invalid Credentials" code:401 data:[1]}, NSLocalizedFailureReason=(Invalid Credentials)}
2014-03-13 12:40:21.026 GPlusDemo[636/0x3d35718c] [lvl=3] __31-[ViewController getPeopleInfo]_block_invoke() Error: Error Domain=com.google.GTLJSONRPCErrorDomain Code=401 "The operation couldn’t be completed. (Invalid Credentials)" UserInfo=0x14d85f90 {error=Invalid Credentials, GTLStructuredError=GTLErrorObject 0x14d85ba0: {message:"Invalid Credentials" code:401 data:[1]}, NSLocalizedFailureReason=(Invalid Credentials)}
I written the following code in ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
GPPSignIn *signIn = [GPPSignIn sharedInstance];
signIn.shouldFetchGooglePlusUser = YES;
//signIn.shouldFetchGoogleUserEmail = YES; // Uncomment to get the user's email
// You previously set kClientId in the "Initialize the Google+ client" step
signIn.clientID = kClientId;
// Uncomment one of these two statements for the scope you chose in the previous step
signIn.scopes = #[ kGTLAuthScopePlusLogin]; // "https://www.googleapis.com/auth/plus.login" scope
signIn.scopes = #[ #"profile" ]; // "profile" scope
// Optional: declare signIn.actions, see "app activities"
signIn.delegate = self;
[signIn trySilentAuthentication];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)refreshInterfaceBasedOnSignIn
{
if ([[GPPSignIn sharedInstance] authentication]) {
// The user is signed in.
NSLog(#"Login");
self.signInButton.hidden = YES;
// Perform other actions here, such as showing a sign-out button
[self getPeopleInfo];
} else {
self.signInButton.hidden = NO;
// Perform other actions here
}
}
- (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];
}
}
- (void)signOut {
[[GPPSignIn sharedInstance] signOut];
}
- (void)disconnect {
[[GPPSignIn sharedInstance] disconnect];
}
- (void)didDisconnectWithError:(NSError *)error {
if (error) {
NSLog(#"Received error %#", error);
} else {
// The user is signed out and disconnected.
// Clean up user data as specified by the Google+ terms.
}
}
-(void)getPeopleInfo
{
GTLServicePlus* plusService = [[GTLServicePlus alloc] init];
plusService.retryEnabled = YES;
[plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];
GTLQueryPlus *query =
[GTLQueryPlus queryForPeopleListWithUserId:#"me"
collection:kGTLPlusCollectionVisible];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPeopleFeed *peopleFeed,
NSError *error) {
if (error) {
GTMLoggerError(#"Error: %#", error);
} else {
// Get an array of people from GTLPlusPeopleFeed
NSArray* peopleList = [peopleFeed.items mutableCopy];
NSLog(#"peopleList:%#", peopleList);
}
}];
}
Call the following method, after login success, for me, i am getting friends list using below method
-(void)finishedWithAuth: (GTMOAuth2Authentication *)auth
error: (NSError *) error {
GTLServicePlus* plusService = [[GTLServicePlus alloc] init];
plusService.retryEnabled = YES;
[plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];
GTLQueryPlus *query =
[GTLQueryPlus queryForPeopleListWithUserId:#"me"
collection:kGTLPlusCollectionVisible];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPeopleFeed *peopleFeed,
NSError *error) {
if (error) {
GTMLoggerError(#"Error: %#", error);
} else {
// Get an array of people from GTLPlusPeopleFeed
NSArray* peopleList = peopleFeed.items;
NSLog(#"peopleList %# ",peopleList);
}
}];
}
As per my experience, Google+ SDK is not having any method fetching the friend list currently.
It's suggested to use Google Contacts API for fetching contacts. It may happen that contacts fetched from this API are not active on Google+. So it's mixed list.
So, Wait for the updates from Google.
We have a way to get google plus visible friends information. Please take a look on description and if it will be not clear enough for you, then I will provide more description.
GTMOAuth2Authentication *auth;
/*That you will get when you login by your google plus account. So I am considering that you already have it.*/
NSMutableArray *arrFriends = [NSMutableArray new];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://www.googleapis.com/plus/v1/people/%#/people/visible?orderBy=alphabetical&access_token=%#",#"your_user_id",auth.accessToken]];
/*When you login via Google plus and fetch your profile information, you will get your user id.*/
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
[request startSynchronous];
if(LOGS_ON) NSLog(#"GooglePlusConnect-->getchGooglePlusFriends-->responseString = %#",request.responseString);
});
Plaease let me know if it is not clear enough for you, then i will provide some more description.
Hi I was also facing same error but it got resolved. The problem is in setting scope.
set the scope as #define kGTLAuthScopePlusLogin #"https://www.googleapis.com/auth/plus.login"
- (void)viewDidLoad
{
[super viewDidLoad];
GPPSignIn *signInG = [GPPSignIn sharedInstance];
signInG.shouldFetchGooglePlusUser = YES;
signInG.shouldFetchGoogleUserEmail = YES;
signInG.clientID = kClientId;
signInG.scopes = # [kGTLAuthScopePlusLogin];
signInG.delegate = self;
[signInG trySilentAuthentication];
}
It will fetch friends details like name, image url but not Email address. For fetching Email address try to use Contact API. iOS has NSXMLParser, the contact api code is given in JS, java, net u could use that and fetch the details.
Hi i was also facing the same problem. This problem Occurring Because of scope.
In Your code You have override the scope.
signIn.scopes = #[ kGTLAuthScopePlusLogin];
With
signIn.scopes = #[ #"profile" ]; // "profile" scope
So, You have to change Your scope By Simple
signIn.scopes = #[ kGTLAuthScopePlusLogin];
Or
signIn.scopes = #[ kGTLAuthScopePlusLogin,#"profile"];
GTLServicePlus* plusService = [[GTLServicePlus alloc] init];
plusService.retryEnabled = YES;
[plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];
GTLQueryPlus *query =
[GTLQueryPlus queryForPeopleListWithUserId:#"me"
collection:kGTLPlusCollectionVisible];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPeopleFeed *peopleFeed,
NSError *error) {
if (error) {
GTMLoggerError(#"Error: %#", error);
} else {
// Get an array of people from GTLPlusPeopleFeed
NSArray* peopleList = peopleFeed.items;
NSLog(#"peopleList %# ",peopleList.description);
for (NSArray *dict in peopleFeed.items) {
NSString *strID=(NSString*)((GTLPlusPerson*)dict).identifier;
NSLog(#"strID %#",strID);
}
}
}];

Resources