简体   繁体   English

解析-PFTwitterUtils:获取用户的电子邮件地址

[英]Parse - PFTwitterUtils: get user's email address

I have an app where you can sign up using Facebook and Twitter via Parse SDK integration. 我有一个应用程序,您可以通过Parse SDK集成使用Facebook和Twitter注册。 This works just fine. 这样很好。

While signing up I need to retrieve the user's email address and save it. 在注册时,我需要检索用户的电子邮件地址并保存它。 This works very easily with the Facebook login but I am unclear on how to do this when the user signs up via Twitter. 这对于使用Facebook登录名非常容易,但是当用户通过Twitter注册时,我不清楚如何执行此操作。

This is the code I am using: 这是我正在使用的代码:

[PFTwitterUtils logInWithBlock:^(PFUser *user, NSError *error) {

    if (!user)
    {
        ...
    }
    else
    {
        NSString * requestString = [NSString stringWithFormat:@"https://api.twitter.com/1.1/users/show.json?screen_name=%@", [PFTwitterUtils twitter].screenName];

        NSURL *verify = [NSURL URLWithString:requestString];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:verify];

        [[PFTwitterUtils twitter] signRequest:request];

        NSError *dataError;
        NSURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:&response
                                                         error:&dataError];
        if (!dataError)
        {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

            ...
        }
    }

}];

Unfortunately the result dictionary does not reveal any email address. 不幸的是结果字典没有显示任何电子邮件地址。

Any help will be much appreciated. 任何帮助都感激不尽。 Thanks in advance! 提前致谢!

This is now possible by filling out a form to request elevated permissions: 现在,可以通过填写表格以请求提升的权限来实现:

Go to https://support.twitter.com/forms/platform Select "I need access to special permissions" 转到https://support.twitter.com/forms/platform选择“我需要访问特殊权限”

Enter Application Name and ID. 输入应用程序名称和ID。 These can be obtained via https://apps.twitter.com/ -- the application ID is the numeric part in the browser's address bar after you click your app. 这些可以通过https://apps.twitter.com/获得-单击您的应用程序后,应用程序ID是浏览器地址栏中的数字部分。

Permissions Request: "Email address" Submit & wait for response 权限请求:“电子邮件地址”提交并等待响应

After your request is granted, an addition permission setting is added in your twitter app's "Permission" section. 批准您的请求后,将在Twitter应用程序的“权限”部分添加一个附加权限设置。 Go to "Additional Permissions" and just tick the checkbox for "Request email addresses from users". 转到“其他权限”,然后选中“从用户请求电子邮件地址”复选框。

Twitter is very sensitive when it comes to passing the email address further along to the developer. Twitter对于将电子邮件地址进一步传递给开发人员非常敏感。 You basically need to show an extra screen asking the user's email address and its explicit consent. 基本上,您需要显示一个额外的屏幕,询问用户的电子邮件地址及其明确同意。

Please note that your Twitter app needs to have access to getting the user's email address for this piece of code to actually return what you need. 请注意,您的Twitter应用程序必须有权获取用户的电子邮件地址,以使这段代码实际返回您所需的内容。 You need whitelist it and to submit for a review, similar to Facebook login permissions. 您需要将其列入白名单并提交审核,类似于Facebook登录权限。 (only apps created via apps.twitter.com and not the ones automatically generated via Fabric. I have a confirmation that the latter ones are not allowed to retrieve the user's email address) (仅通过apps.twitter.com创建的应用程序,而不是通过Fabric自动生成的应用程序。我确认不允许后者检索用户的电子邮件地址)

This is a complete working example of a Twitter signup/login flow (what interests you is in the if ! block): 这是Twitter注册/登录流程的完整示例(您对if!块感兴趣的地方):

 - (IBAction)loginWithTwitter:(id)sender {
        [[Twitter sharedInstance] logInWithCompletion:^
         (TWTRSession *session, NSError *error) {
             if (error) {
                 // You can show an UI alert with the error.localizedDescription
             } else {
                 // you can show any progress hud here (to prevent UI changes)
                 [ConnectionManager loginWithSocialProvider:LoginMethodTypeTwitter token:session.authToken success:^(id responseObj) {
                     NSLog(@"response from twitter login : %@", responseObj);
                     // dismiss your progress hud here (unless you perform additional network calls)
                     BOOL userExists = ![[responseObj valueForKey:@"UserNotFound"] boolValue]; // this is a check in my custom API response - if the user exists
                     if (userExists) {
                         // perform a login here with the above credentials
                     } else {
                         TWTRShareEmailViewController* shareEmailViewController =
                         [[TWTRShareEmailViewController alloc]
                          initWithCompletion:^(NSString* email, NSError* error) {
                              NSLog(@"Email %@, Error: %@", email, error);
                              [self launchPostSignupWithName:nil email:email token:session.authToken username:session.userName provider:LoginMethodTypeTwitter];
                          }];
                         // The code is being called on the main thread already. this is fail proof
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [self presentViewController:shareEmailViewController
                                                animated:YES
                                              completion:nil];
                         });                     
                     }
                 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                     // show an alert here and dismiss your progress hud as well, if any
                 }];
             }
         }];
    }

Swift version of Danut Pralea response Swift版本的Danut Pralea回应

let twitterUserID = PFTwitterUtils.twitter()?.userId
let twitterScreenName = PFTwitterUtils.twitter()?.screenName

var twitterURL = "https://api.twitter.com/1.1/users/show.json?"
if let userID = twitterUserID{
    twitterURL = twitterURL + "user_id=" + userID
}else if let screenName = twitterScreenName{
    twitterURL = twitterURL + "screen_name=" + screenName
}else{
    print("Something's not right")
    return
}

let verify = NSURL(string: twitterURL)
let request = NSMutableURLRequest(URL: verify!)
PFTwitterUtils.twitter()?.signRequest(request)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
    if error == nil{

        do {
            let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
            guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
                print("Not a Dictionary")
                // put in function
                return
            }
            print("JSONDictionary! \(JSONDictionary)")

            let user = PFUser.currentUser()

            let profileImage = JSONDictionary["profile_image_url_https"] as! String
            if !profileImage.isEmpty{
                user!["profileImageAvatar"] = profileImage
            }

            let screenName = JSONDictionary["screen_name"] as! String
            if !screenName.isEmpty{
                user!["screen_name"] = screenName
            }

            let userName = JSONDictionary["name"] as! String
            if !userName.isEmpty{
                user!["username"] = userName
            }else if !screenName.isEmpty{
                user!["username"] = screenName
            }

            user?.saveInBackgroundWithBlock({ (status, error) -> Void in
                if error == nil{
                    print("twitter data saved")
                }else{
                    print("error saving twitter data")
                    print(error)
                }
            })
        }
        catch let JSONError as NSError {
            print("\(JSONError)")
        }


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用电子邮件地址作为用户名时无法重置解析用户的密码 - Unable to reset Parse user's password when using email address as username 在IOS上使用Parse的PFTwitterUtils登录Twitter时,NSURLErrorDomain错误1012 - NSURLErrorDomain Error 1012 when logging into twitter using Parse's PFTwitterUtils on IOS iOS:无法获取用户的电子邮件地址 - iOS : Can't get the user email address Google+不会返回用户的朋友的电子邮件地址 - Google+ does not return user's friend's email address 如何使用Firebase在iOS上验证用户的电子邮件地址? - How to verify a user's email address on iOS with Firebase? 解析iOS PFTwitterUtils链接用户:不执行任何操作 - Parse iOS PFTwitterUtils linkUser: doesn't do anything 使用Parse.com API时出现PFTwitterUtils错误-iOS - PFTwitterUtils error when using Parse.com API - iOS 如何在swift iOS for iPhone中使用FBSDK获取用户电子邮件地址? - How to get user email address using FBSDK in swift iOS for iPhone? 从iOS中的Twitter获取用户个人资料详细信息(尤其是电子邮件地址) - Get user profile details (especially email address) from Twitter in iOS 使用FBgraphUser在解析中从Facebook获取用户电子邮件 - get user email from Facebook Using FBgraphUser In Parse
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM