3

I am aiming to get a user's details based on his/her Twitter account. Now first of all, let me explain what I want to do.

In my case, user will be presented an option to Sign-up with Twitter account. So, based on user's Twitter account, I want to be able to get user details (e.g. email-id, name, profile picture, birth date, gender etc..) and save those details in database. Now, many people will probably suggest me to use ACAccount and ACAccountStore, a class that provides an interface for accessing, manipulating, and storing accounts. But in my case, I want to sign up user, even if user has not configured an account for Twitter in iOS Settings App. I want user to navigate to login screen of Twitter (in Safari or in App itself, or using any other alternative).

I have also referred the documentation of Twitter having API list here. But I am a lot confused how user should be presented a login screen to log into the Twitter account and how I will get profile information. Should I use UIWebView, or redirect user to Safari or adopt another way for that ?

halfer
  • 19,824
  • 17
  • 99
  • 186
NSPratik
  • 4,714
  • 7
  • 51
  • 81

5 Answers5

5

Finally, after having a long conversation with sdk-feedback@twitter.com, I got my App whitelisted. Here is the story:

  • Send mail to sdk-feedback@twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email address inside your App.

  • They will review your App and reply to you within 2-3 business days.

  • Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:

    1. On the 'Settings' tab, add a terms of service and privacy policy URL
    2. On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.

Put your hands on code:

Agree with statement of Vizllx: "Twitter has provided a beautiful framework for that, you just have to integrate it in your app."

Get user email address

-(void)requestUserEmail
    {
        if ([[Twitter sharedInstance] session]) {

            TWTRShareEmailViewController *shareEmailViewController =
            [[TWTRShareEmailViewController alloc]
             initWithCompletion:^(NSString *email, NSError *error) {
                 NSLog(@"Email %@ | Error: %@", email, error);
             }];

            [self presentViewController:shareEmailViewController
                               animated:YES
                             completion:nil];
        } else {
            // Handle user not signed in (e.g. attempt to log in or show an alert)
        }
    }

Get user profile

-(void)usersShow:(NSString *)userID
{
    NSString *statusesShowEndpoint = @"https://api.twitter.com/1.1/users/show.json";
    NSDictionary *params = @{@"user_id": userID};

    NSError *clientError;
    NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
                             URLRequestWithMethod:@"GET"
                             URL:statusesShowEndpoint
                             parameters:params
                             error:&clientError];

    if (request) {
        [[[Twitter sharedInstance] APIClient]
         sendTwitterRequest:request
         completion:^(NSURLResponse *response,
                      NSData *data,
                      NSError *connectionError) {
             if (data) {
                 // handle the response data e.g.
                 NSError *jsonError;
                 NSDictionary *json = [NSJSONSerialization
                                       JSONObjectWithData:data
                                       options:0
                                       error:&jsonError];
                 NSLog(@"%@",[json description]);
             }
             else {
                 NSLog(@"Error code: %ld | Error description: %@", (long)[connectionError code], [connectionError localizedDescription]);
             }
         }];
    }
    else {
        NSLog(@"Error: %@", clientError);
    }
}

Hope it helps !!!

Community
  • 1
  • 1
NSPratik
  • 4,714
  • 7
  • 51
  • 81
  • @NSPrtatik I saw your answers for various posts. Can you please see this question http://stackoverflow.com/questions/32758067/whitelisted-ios-app-by-twitter-still-not-getting-email-of-user – Apple_Magic Sep 24 '15 at 16:32
4

How to get email id in twitter ?

Step 1 : got to https://apps.twitter.com/app/

Step 2 : click on ur app > click on permission tab .

Step 3 : here check the email box

enter image description here

Harshil Kotecha
  • 2,846
  • 4
  • 27
  • 41
3

In Twitter you can get user_name and user_id only. It is that much secure that you can't fetch email id, birth date, gender etc.., compare to Facebook, Twitter is very confidential for supplying the data.

need ref: link1.

Community
  • 1
  • 1
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • In the documentation of Twitter, they have mentioned the method to get user email id. Also I got some example to download user profile pictures. – NSPratik May 14 '15 at 10:36
  • 1
    ya we can fetch user picture when u passing the **screen_name** after that we fetch the image , in here I attach the image please refer that link – Anbu.Karthik May 14 '15 at 10:38
  • 1
    in my knowledge I used twitter api in last 8 or 9 projects, we can't fetch the email Id in **Account** framework please see this ref [link2](http://stackoverflow.com/questions/19629338/how-to-get-user-email-address-via-twitter-api-in-ios) – Anbu.Karthik May 14 '15 at 10:40
  • 1
    may be some third_parties provide this , I am not seen, if you need anything I surely hope with you friend – Anbu.Karthik May 14 '15 at 10:43
  • Anbu.Karthik, please check my added answer. It's possible and I am now able to get user email address. – NSPratik May 27 '15 at 08:00
3

Twitter has provided a beautiful framework for that, you just have to integrate it in your app.

https://dev.twitter.com/twitter-kit/ios

It has a simple Login Method:-

// Objective-C
TWTRLogInButton* logInButton =  [TWTRLogInButton
                                     buttonWithLogInCompletion:
                                     ^(TWTRSession* session, NSError* error) {
    if (session) {
         NSLog(@"signed in as %@", [session userName]);
    } else {
         NSLog(@"error: %@", [error localizedDescription]);
    }
}];
logInButton.center = self.view.center;
[self.view addSubview:logInButton];

This is the process to get user profile information:-

/* Get user info */
        [[[Twitter sharedInstance] APIClient] loadUserWithID:[session userID]
                                                  completion:^(TWTRUser *user,
                                                               NSError *error)
        {
            // handle the response or error
            if (![error isEqual:nil]) {
                NSLog(@"Twitter info   -> user = %@ ",user);
                NSString *urlString = [[NSString alloc]initWithString:user.profileImageLargeURL];
                NSURL *url = [[NSURL alloc]initWithString:urlString];
                NSData *pullTwitterPP = [[NSData alloc]initWithContentsOfURL:url];

                UIImage *profImage = [UIImage imageWithData:pullTwitterPP];


            } else {
                NSLog(@"Twitter error getting profile : %@", [error localizedDescription]);
            }
        }];

I think rest you can find from Twitter Kit Tutorial, it also allows to request a user’s email, by calling the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback.

Vizllx
  • 9,135
  • 1
  • 41
  • 79
  • We can't get email using Twitter APIs. Twitter don't allow exposing user email address. – NSPratik May 14 '15 at 13:01
  • 1
    Who said it is not possible, Twitter Kit allows to request a user’s email, call the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback. Read carefully the Twitter Kit doc then comment. – Vizllx May 14 '15 at 14:32
  • I referred to lots of posts saying that it's not possible and I also read the documentation of Twitter. As per their documentation, if we need a user email address then our App should be shortlisted by then... – NSPratik May 15 '15 at 05:39
  • I decided to use Twitter kit. Answer accepted... Everything works fine. Just I will have to make my App white-listed on Twitter to request user his/her email address. Presently I am getting _nil_ as email address. – NSPratik May 19 '15 at 10:51
  • @Pratik Check the 3rd comment, email fetching is possible, you just have to read the docs carefully. – Vizllx May 19 '15 at 11:26
  • Vizllx, I explored a lot in web but could not find a way to call the TwitterAuthClient#requestEmail method as suggested by you. Also, as per Twitter documentation, we will have to fill up a form [here](https://dev.twitter.com/twitter-kit/android/request-email). But there is no option for requesting user email. Please help me. I am desperate to the solution. – NSPratik May 26 '15 at 10:10
2

In Swift 4.2 and Xcode 10.1

It's getting email also.

import TwitterKit 


@IBAction func onClickTwitterSignin(_ sender: UIButton) {

    TWTRTwitter.sharedInstance().logIn { (session, error) in
    if (session != nil) {
        let name = session?.userName ?? ""
        print(name)
        print(session?.userID  ?? "")
        print(session?.authToken  ?? "")
        print(session?.authTokenSecret  ?? "")
        let client = TWTRAPIClient.withCurrentUser()
        client.requestEmail { email, error in
            if (email != nil) {
                let recivedEmailID = email ?? ""
                print(recivedEmailID)
            }else {
                print("error--: \(String(describing: error?.localizedDescription))");
            }
        }
            //To get profile image url and screen name
            let twitterClient = TWTRAPIClient(userID: session?.userID)
                twitterClient.loadUser(withID: session?.userID ?? "") {(user, error) in
                print(user?.profileImageURL ?? "")
                print(user?.profileImageLargeURL ?? "")
                print(user?.screenName ?? "")
            }
        let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as!   SecondViewController
        self.navigationController?.pushViewController(storyboard, animated: true)
    }else {
        print("error: \(String(describing: error?.localizedDescription))");
    }
    }
}

Follow the Harshil Kotecha answer.

Step 1 : got to https://apps.twitter.com/app/

Step 2 : click on ur app > click on permission tab .

Step 3 : here check the email box

enter image description here

If you want to logout

let store = TWTRTwitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
    print(store.session()?.userID ?? "")
    store.logOutUserID(userID)
    print(store.session()?.userID ?? "")
    self.navigationController?.popToRootViewController(animated: true)
}
Naresh
  • 16,698
  • 6
  • 112
  • 113