Get Google contacts using API on iOS
This question was made more difficult by the number of Google API versions in the last few years and also how rarely users actually login with their Google details. This means there is little documentation due to the lack of demand. I finally managed to get it working with the help of this great swift tutorial by App Code. This tutorial is rare as it goes through the entire signin process step by step as well as covering contact look up which I what I was after.
I would recommend going through this tutorial start to finish but I will also put some of the most important information here.
The first thing to do is ensure you have added your app correctly to the Google Console here. Make sure to add the Google+ API and get your client ID.
Second you need to set up your Google sign in. This is pretty easy and there are some great resources for setting this up. I would recommend this Google youtube video but there are a lot of other resources online. I won't go into detail as this is not the point of the question.
Next you need to set your sign in code up.
Make sure you have added both the delegates to your viewController
<GIDSignInDelegate, GIDSignInUIDelegate
and also configured it in the viewDidLoad:
[GIDSignIn sharedInstance].delegate = self;
[GIDSignIn sharedInstance].uiDelegate = self;
[GIDSignIn sharedInstance].clientID = @"123456789012-thisismadeup12345678901234567890.apps.googleusercontent.com";
[[GIDSignIn sharedInstance] setScopes:@[@"https://www.googleapis.com/auth/plus.login", @"https://www.googleapis.com/auth/plus.me"]];
None of the answers I found elsewhere had me setting my clientID (from google console) but the important part is adding the scopes code, without this you haven't got the correct permissions to get contacts.
At this stage you can check if everything is set up correctly. Load up your app and click the Google login button and it should load up the webview and ask you to confirm your permissions. It should look like this:
The important permissions are the top two. If you only have the bottom two you will only be able to access your own profile and not those of your friends.
Once you have got this far you only need to perform the correct API call to return your friends. This is easier said than done with the pure number of different ones on different Google websites. I completed mine with the following:
NSString * urlString = [NSString stringWithFormat:@"https://www.googleapis.com/plus/v1/people/me/people/visible?access_token=%@", [GIDSignIn sharedInstance].currentUser.authentication.accessToken];
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = responseSerializer;
[manager GET:path parameters:params success:^(AFHTTPRequestOperation * operation, id responseObject) {
if (![responseObject isEqual: [NSNull null]]) {
if(responseObject[@"error"]) {
NSError * error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedDescriptionKey: responseObject[@"error"]}];
}
else {
// We now have our response object
}
}
else {
// response is nil
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Failure
}];
You will need to add AFNetworking to your project and this is a custom function for my project so might not be copy past-able.
This though should return a dictionary of all your contacts which you can then use.
How can I use Google's people API in Xamarin.iOS?
I have solved it by using Xamarin.Auth library.
Auth = new OAuth2Authenticator(
Configuration.ClientId,
string.Empty,
"https://www.googleapis.com/auth/contacts",
new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
new Uri(Configuration.RedirectUrl),
new Uri("https://www.googleapis.com/oauth2/v4/token"),
isUsingNativeUI: true);
var viewController = Auth.GetUI();
PresentViewController(viewController, true, null);
Auth.Completed += Auth_Completed;
Auth.Error += Auth_Error;
private void Auth_Error(object sender, AuthenticatorErrorEventArgs e)
{
}
private void Auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
// SFSafariViewController doesn't dismiss itself
DismissViewController(true, null);
if (e.IsAuthenticated)
{
}
}
Must implement OpentUrl() in Appdelegate.cs calss upto iOS 12 and above iOS 13 implement OpenUrlContexts() method in SceneDelegate.cs
Related Topics
How to Calculate Current Location in Watchkit Extension
Nspredicate to Match "Any Entry in an Nsdatabase with Value That Contains a String"
How to Comment or Like a Photo in Facebook Through Fbconnect or Graph API in iPhone Sdk
How to Convert Image into Binary Format in iOS
How to Overlay One Video on Another in iOS
Rec iOS Conversations. Where to Start
How to Use Nsurlsession to Determine If Resource Has Changed
Allow "Auto Lock" While Video Is Being Played
How to Change Text Font in Uipickerview in iOS 7
How to Change iPhone Uitableview Delete Button Title While Editing It
Could Not Cast Value of Type 'Uiview' (0X112484Eb0) to 'Skview' (0X111646718)
Multiple Localized .Strings Files in iOS App Bundle
Multiple Uitableview in Single Viewcontroller
How to Use Avcapturephotooutput to Capture Photo Swift + Xcode