Search code examples
iosswifttwitterparse-platformpfuser

Getting Twitter user details using swift


I have been searching since few days on how I can get user details based on his/her Twitter account ,I'm using twitter login in my application & I haven't found anything about this in Swift, so i'm asking! How can I get the username & email & uprofile Image of a logged in User with Parse from Twitter in order to save them on parse cloud?


Solution

  • You can access the username and userID of the logged-in user pretty easily. Inside most Twitter login methods you'll see something like this:

    @IBAction func loginTwitter(sender: UIBarButtonItem) {
        Twitter.sharedInstance().logInWithCompletion {
            (session, error) -> Void in
            if (session != nil) {
    
                print(session?.userName)
                print(session?.userID)
            } else {
                print("error")
    
            }
        }
    }
    

    Twitter does not expose the email address of users as far as I'm aware.

    For the profile image you'll need to send a GET request. Here is some code that may not be up to date with the latest TwitterKit version but should at least give you a sense of how the request should be formatted.

    func getUserInfo(screenName : String){
        if let userID = Twitter.sharedInstance().sessionStore.session()!.userID {
            let client = TWTRAPIClient(userID: userID)
            let url = "https://api.twitter.com/1.1/users/show.json"
            let params = ["screen_name": screenName]
            var clientError : NSError?
            let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("GET", URL: url, parameters: params, error: &clientError)
    
            client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
                if let someData = data {
                    do {
                        let results = try NSJSONSerialization.JSONObjectWithData(someData, options: .AllowFragments) as! NSDictionary
                        print(results)
    
                    } catch {
                    }
                }
            }
        }
    }
    

    You'll need to go through the JSON that gets returned and find "profile_image_url_https" a couple levels down.

    Good Luck!