如何通过Twitter API在iOS中获取用户电子邮件地址?

6

我尝试了多个SDK,但没有从任何资源中获取到电子邮件ID。 我尝试过 FHSTwitterEngine ,但没有得到解决方案。

FHSTwitterEngine *twitterEngine = [FHSTwitterEngine sharedEngine];
NSString *username = [twitterEngine loggedInUsername]; //self.engine.loggedInUsername;
NSString *key = [twitterEngine accessToken].key;
NSString *secrete = [twitterEngine accessToken].secret;

if (username.length > 0)
{
    NSDictionary *userProfile = [[FHSTwitterEngine sharedEngine] getProfileUsername:username];
    NSLog(@"userProfile: %@", userProfile);

您的代码示例似乎不完整..? - Chris Kempen
我喜欢FHSTwitterEngine哈哈 - Nate Symer
5个回答

13

编辑

Twitter更新了API,现在用户可以使用TWTRShareEmailViewController类来获取电子邮件。

// Objective-C
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 {
  // TODO: Handle user not signed in (e.g. attempt to log in or show an alert)
}

// Swift
if Twitter.sharedInstance().session {
  let shareEmailViewController = TWTRShareEmailViewController() { email, error in
    println("Email \(email), Error: \(error)")
  }
  self.presentViewController(shareEmailViewController, animated: true, completion: nil)
} else {
  // TODO: Handle user not signed in (e.g. attempt to log in or show an alert)
}

注: 即使用户授权了其电子邮件地址,也不能保证您能获取到电子邮件地址。例如,如果有人用手机号码而不是电子邮件地址注册 Twitter,则电子邮件字段可能为空。当出现这种情况时,完成块将传递一个错误,因为没有可用的电子邮件地址。

Twitter 开发者文档


过去

您无法获得 Twitter 用户的电子邮件地址。

Twitter API 在 OAuth 令牌协商过程中不会提供用户的电子邮件地址,也没有其他方式来获取它。

Twitter 文档


2
这个已经不正确了。可以通过以下方式获取用户的电子邮件地址:/1.1/account/verify_credentials.json?include_email=true - BreadicalMD
链接不存在 @Virussmca - Leena
https://dev.twitter.com/rest/reference/get/account/verify_credentials 可用于获取电子邮件ID,但您的应用程序必须先被加入白名单。 - Naveen Ramanathan

4

您需要使用 Twitter框架。Twitter为此提供了一个漂亮的框架,您只需要将其集成到您的应用程序中即可。

要获取用户电子邮件地址,您的应用程序需要被加入白名单。以下是链接。请前往此表格。您可以向sdk-feedback@twitter.com发送一封邮件,其中包含有关您的应用程序的一些详细信息,例如Consumer key、App Store链接、隐私政策链接、元数据、我们的应用程序登录说明等等。他们将在2-3个工作日内回复。

以下是我如何通过与Twitter支持团队会话获得白名单的故事:

  • sdk-feedback@twitter.com发送一封邮件,其中包含有关您的应用程序的一些详细信息,例如Consumer key、App Store链接、隐私政策链接、元数据、我们的应用程序登录说明,并在邮件中提到您想在您的应用程序中访问用户电子邮件地址。

  • 他们将审核您的应用程序,并在2-3个工作日内回复您。

  • 一旦他们说您的应用程序被白名单所接受,就更新Twitter开发人员门户网站中您的应用程序设置。登录到apps.twitter.com

    1. 在“设置”选项卡上添加服务条款和隐私政策URL
    2. 在“权限”选项卡上,将您的令牌范围更改为请求电子邮件。此选项仅在您的应用程序被加入白名单后才能看到。

动手写代码

使用Twitter框架:

获取用户电子邮件地址

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

获取用户资料

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

希望这有所帮助!

2
如果您想要获取用户的电子邮件地址,您需要在自己的应用程序和服务范围内向用户请求。Twitter API在OAuth令牌协商过程中不会提供用户的电子邮件地址,也没有其他获取方式。请注意保留HTML标签。

0
在Swift 4.2和Xcode 10.1中,它还可以获取电子邮件。
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))");
            }
        }
        let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
        self.navigationController?.pushViewController(storyboard, animated: true)
    }else {
        print("error: \(String(describing: error?.localizedDescription))");
    }
}
}

0

Swift 3-4

@IBAction func btnTwitterAction(_ sender: Any) {

        TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in
            if (session != nil) {
                print("signed in as \(String(describing: session?.userName))");
                if let mySession = session{

                    let client = TWTRAPIClient.withCurrentUser()
                    //To get User name and email
                    client.requestEmail { email, error in
                        if (email != nil) {
                            print("signed in as \(String(describing: session?.userName))");
                            let firstName = session?.userName ?? ""   // received first name
                            let lastName = session?.userName ?? ""  // received last name
                            let recivedEmailID = email ?? ""   // received email

                        }else {
                            print("error: \(String(describing: error?.localizedDescription))");
                        }
                    }


                    //To get user profile picture
                    client.loadUser(withID: session?.userID, completion: { (userData, error) in
                        if (userData != nil) {

                            let fullName = userData.name //Full Name
                            let userProfileImage = userData.profileImageLargeURL //User Profile Image
                            let userTwitterProfileUrl = userData?.profileURL // User TwitterProfileUrl
                        }
                    })
                }
            } else {
                print("error: \(error?.localizedDescription)");
            }
        })

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接