Get user profile details (especially email address) from Twitter in iOS

余生颓废 提交于 2019-11-26 18:25:06

问题


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 ?


回答1:


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.




回答2:


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 !!!




回答3:


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




回答4:


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.




回答5:


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

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)
}


来源:https://stackoverflow.com/questions/30235010/get-user-profile-details-especially-email-address-from-twitter-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!