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

时间:2014-08-22 08:06:31

标签: ios xcode email twitter parse-platform

我有一个应用程序,您可以通过Parse SDK集成使用Facebook和Twitter注册。这很好用。

注册时,我需要检索用户的电子邮件地址并保存。这可以通过Facebook登录轻松工作,但我不清楚当用户通过Twitter注册时如何做到这一点。

这是我正在使用的代码:

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

            ...
        }
    }

}];

不幸的是,结果字典没有显示任何电子邮件地址。

任何帮助将不胜感激。提前谢谢!

3 个答案:

答案 0 :(得分:1)

现在可以通过填写表单来请求提升权限:

转到https://support.twitter.com/forms/platform 选择"我需要访问特殊权限"

输入应用程序名称和ID。这些可以通过https://apps.twitter.com/获得 - 点击您的应用后,应用ID就是浏览器地址栏中的数字部分。

权限请求:"电子邮件地址" 提交&等待回应

在您的请求被授予后,您的Twitter应用程序中将添加一项添加权限设置"权限"部分。转到"其他权限"然后勾选"从用户那里请求电子邮件地址"。

的复选框

答案 1 :(得分:0)

Twitter将电子邮件地址进一步传递给开发人员时非常敏感。您基本上需要显示一个额外的屏幕,询问用户的电子邮件地址及其明确的同意。

请注意,您的Twitter应用程序需要有权访问此用户代码的用户电子邮件地址,以实际返回您所需的内容。您需要将其列入白名单并提交审核,类似于Facebook登录权限。 (仅通过apps.twitter.com创建的应用程序,而不是通过Fabric自动生成的应用程序。我确认后者不允许检索用户的电子邮件地址)

这是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
                 }];
             }
         }];
    }

答案 2 :(得分:0)

Danut Pralea响应的Swift版本

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


    }
}