在 iOS 中从 Twitter 获取用户个人资料详细信息(尤其是电子邮件地址)

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

我的目标是根据 his/her Twitter 帐户获取用户的详细信息。现在首先让我解释一下我想做什么。

在我的案例中,用户将看到一个选项,可以使用 Twitter 帐户注册。因此,基于用户的 Twitter 帐户,我希望能够获取用户详细信息(例如电子邮件 ID、姓名、个人资料图片、出生日期、性别等)并将这些详细信息保存在数据库中。现在,很多人可能会建议我使用 ACAccountACAccountStore,一个 class,它提供了一个用于访问、操作和存储帐户的接口。但就我而言,我想注册用户,即使用户尚未在 iOS 设置应用程序中为 Twitter 配置帐户。我希望用户导航到 Twitter 的登录屏幕(在 Safari 或应用程序本身中,或使用任何其他替代方法)。

我还参考了具有 API 列表 here 的 Twitter 文档。但是我很困惑应该如何向用户显示登录屏幕以登录 Twitter 帐户以及我将如何获取个人资料信息。我应该使用 UIWebView,还是将用户重定向到 Safari 或采用其他方式?

在 Twitter 中,您只能获得 user_nameuser_id。你不能获取 email idbirth dategender 等,这是非常安全的。与 Facebook 相比,Twitter 在提供数据方面非常保密。

需要参考:link1.

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

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

它有一个简单的登录方法:-

// 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];

这是获取用户资料信息的过程:-

/* 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]);
            }
        }];

我想你可以从 Twitter Kit 教程中找到其他内容,它还允许通过调用 TwitterAuthClient#requestEmail 方法,传入有效的 TwitterSession 和回调来请求用户的电子邮件。

最后,在与 sdk-feedback@twitter.com 进行了长时间的交谈后,我将我的应用程序列入了白名单。这是故事:

  • 发送邮件至 sdk-feedback@twitter.com,其中包含有关您的应用程序的一些详细信息,例如消费者密钥、应用程序的应用程序商店 link、Link 隐私政策、元数据、有关如何登录我们的应用程序的说明。在邮件中提及您想要在您的应用程序中访问用户电子邮件地址。

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

  • 一旦他们说您的应用已列入白名单,请在 Twitter 开发者门户中更新您的应用设置。登录 apps.twitter.com 和:

    1. 在 'Settings' 选项卡上,添加服务条款和隐私政策 URL
    2. 在 'Permissions' 选项卡上,将令牌的范围更改为请求电子邮件。只有在您的应用程序被列入白名单后,才会看到此选项。

动手编写代码:

同意Vizllx的说法:"Twitter has provided a beautiful framework for that, you just have to integrate it in your app."

获取用户邮箱地址

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

希望对您有所帮助!!!

如何在 Twitter 中获取电子邮件 ID?

第 1 步:到达 https://apps.twitter.com/app/

第 2 步:点击您的应用 > 点击权限选项卡。

第 3 步:在这里检查邮箱

在 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))");
            }
        }
            //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))");
    }
    }
}

关注 Harshil Kotecha 的回答。

第 1 步:到达 https://apps.twitter.com/app/

第 2 步:点击您的应用 > 点击权限选项卡。

第 3 步:在这里检查邮箱

如果你想退出

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