I am aiming to get a user's details based on his/her Twitter account. Now first of all, let me explain what I want to do.
In my case, user will be presented an option to Sign-up with Twitter account. So, based on user's Twitter account, I want to be able to get user details (e.g. email-id, name, profile picture, birth date, gender etc..) and save those details in database. Now, many people will probably suggest me to use ACAccount and ACAccountStore, a class that provides an interface for accessing, manipulating, and storing accounts. But in my case, I want to sign up user, even if user has not configured an account for Twitter in iOS Settings App. I want user to navigate to login screen of Twitter (in Safari or in App itself, or using any other alternative).
I have also referred the documentation of Twitter having API list here. But I am a lot confused how user should be presented a login screen to log into the Twitter account and how I will get profile information. Should I use UIWebView, or redirect user to Safari or adopt another way for that ?
Finally, after having a long conversation with sdk-feedback#twitter.com, I got my App whitelisted. Here is the story:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email address inside your App.
They will review your App and reply to you within 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
Put your hands on code:
Agree with statement of Vizllx: "Twitter has provided a beautiful framework for that, you just have to integrate it in your app."
Get user email address
-(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)
}
}
Get user profile
-(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);
}
}
Hope it helps !!!
How to get email id in twitter ?
Step 1 : got to https://apps.twitter.com/app/
Step 2 : click on ur app > click on permission tab .
Step 3 : here check the email box
Twitter has provided a beautiful framework for that, you just have to integrate it in your app.
https://dev.twitter.com/twitter-kit/ios
It has a simple Login Method:-
// 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];
This is the process to get user profile information:-
/* 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]);
}
}];
I think rest you can find from Twitter Kit Tutorial, it also allows to request a user’s email, by calling the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback.
In Twitter you can get user_name and user_id only. It is that much secure that you can't fetch email id, birth date, gender etc.., compare to Facebook, Twitter is very confidential for supplying the data.
need ref: link1.
In Swift 4.2 and Xcode 10.1
It's getting email also.
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))");
}
}
}
Follow the Harshil Kotecha answer.
Step 1 : got to https://apps.twitter.com/app/
Step 2 : click on ur app > click on permission tab .
Step 3 : here check the email box
If you want to logout
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)
}
Related
I want post something on Facebook. I have used SLComposeViewController for that. I just want to ask how can i share if user hasn't configured its app in phone.
Is there any way that I open it in browser and then post anything. Consider I want to post any string say "hello there" . So i keep this string , open safari and login there . After I am logged in the string is posted automatically
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
let fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbShare.completionHandler = {
result in
switch result {
case SLComposeViewControllerResult.Cancelled:
//Code to deal with it being cancelled
break
case SLComposeViewControllerResult.Done:
//Code here to deal with it being completed
break
}
}
refrenceViewController.presentViewController(fbShare, animated: true, completion: nil)
} else {
//open safari and post it there
}
I used the following code to post videos to facebook. You can use similar approach to post your text.
NSData *data = [NSData dataWithContentsOfURL:outputFileURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
data, #"video.mp4",
#"video/mp4", #"contentType",
caption, #"description",
nil];
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if(!error) {
DDLogDebug(#"result %#",result);
} else {
DDLogError(#"error description : %#",error.description);
[Helper showToast:[NSString stringWithFormat:#"Unable to share to Facebook : Error: %#",[error localizedDescription]] withDuration:1];
}
}];
of course before this you need to make sure that you already have the FBSDKAccess token granted. You can check the full documentation from facebook sdk
https://developers.facebook.com/docs/ios/graph
I am trying my hands on new fabric twitter kit for iOS.
After signing in we can ask user to allow access for the email id and if it allows then returns email of the logged in user but it giving me error.
Email (null), Error: Error Domain=NSURLErrorDomain Code=-1001
"The request timed out." UserInfo=0x7fdd314f1c30
{NSUnderlyingError=0x7fdd314d9aa0 "The request timed out.",
NSErrorFailingURLStringKey=https://api.twitter.com/1.1/account/verify_cre
dentials.json?skip_status=true&include_email=true,
NSErrorFailingURLKey=https://api.twitter.com/1.1/account/verify_credentia
ls.json?skip_status=true&include_email=true,
NSLocalizedDescription=The request timed out.}
And here is my code that i've tried from their doc.
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)
}
Is anything wrong in my code? Please help me.
I can post my status and media to twitter but can't get email Id.
Can anyone please help me in this problem? I'm also new to development.
To get user email address, your application should be whitelisted. Here is the link. Go to use this form. You can either send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App etc..They will respond within 2-3 working days.
Here is the story how I got whitelisted by conversation with Twitter support team:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email adress inside your App.
They will review your App and reply to you withing 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
Put your hands on code
Use of Twitter framework:
Get user email address
-(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)
}
}
Get user profile
-(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);
}
}
Hope it helps !!!
I'd like to request the user's Twitter mail. On https://dev.twitter.com/twitter-kit/ios/request-email
Code is:
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController* shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString* email, NSError* error) {
if (error)
{
NSLog(#"Error %#",error.localizedDescription);
}else
{
NSLog(#"Email %#",email);
}
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
}
use this link https://support.twitter.com/forms/platform to submit a request for your app to be granted for user's email address. Choose any one of the the options and fill all the information.
Here is the example after you get permission:
check on this URL : https://apps.twitter.com/app/APP_ID/permissions
I have made a basic app using Twitter's fabric that allows user to tweet within my app and Provide Login With Twitter.Every things works a I Wanted.
How my app Works
If the user doesn't logged in to twitter my app allows him to login and if he is login then directly allows him to tweet.
Now the Big Part Comes
As I saw in many Apps I Can Remove my signed account from the app.And I am not able to get any method that help me to achieve this. I want to allow user to logout from twitter within my app whenever he/She wants.
I googled but i doesn't find anything
Here Is my Code:
- (IBAction)LogOut:(id)sender
{
[[Twitter sharedInstance]logOut];
}
- (IBAction)LogMeIn:(id)sender
{
[[Twitter sharedInstance] logInWithCompletion:^
(TWTRSession *session, NSError *error) {
if (session) {
NSLog(#"signed in as %#", [session userName]);
[LoginButton setTitle:#"LogOut" forState:normal];
} else {
NSLog(#"error: %#", [error localizedDescription]);
}
}];
}
this was a problem with NSCookie from Foundation framework And i slove this issues with help of below code
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
for (NSHTTPCookie *cookie in cookies)
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
You need to use below code
[[[Twitter sharedInstance] sessionStore] logOutUserID:USERID];
Provide user id of the user you want to logout.
UPDATE: May 2016 - Framework has changed so this answer is no longer relevant.
See this answer:
https://stackoverflow.com/a/35765833/940709
and this answer:
https://stackoverflow.com/a/30916904/940709 instead.
[[[Twitter sharedInstance] sessionStore] logOutUserID:USERID];
This is the best simple answer for Swift 3:
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}
or you can use Naeem's answer but add () after store.session
Logout Code From Twitter Docs:
Objective-C
TWTRSessionStore *store = [[Twitter sharedInstance] sessionStore];
NSString *userID = store.session.userID;
[store logOutUserID:userID];
Swift
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}
For Swift try this,
/**
* Deletes the local Twitter user session from this app. This will not remove the system Twitter account nor make a network request to invalidate the session.
*
* #param userID ID of the user to log out
*/
Twitter.sharedInstance().sessionStore.logOutUserID(userId)
First make sure some user is signed in, then perform logout.
NSString *signedInUserID = [TWTRAPIClient clientWithCurrentUser].userID;
if (signedInUserID) {
[[Twitter sharedInstance].sessionStore logoutUserID:signedInUserID];
}
While login mention method as webBasedForceLogin, so that it will not create entry into Safari Cache.
private func twitterLogin() {
Twitter.sharedInstance().logIn(withMethods: .webBasedForceLogin, completion: { (session, error) in
if let error = error {
print(error.localizedDescription)
}
guard let session = session else {
return
}
print("success! Welcome \(session.userName).")
self.twitterButton.setTitle("TWITTER LOGOUT", for: .normal)
})
}
private func twitterLogout() {
let sessionStore = Twitter.sharedInstance().sessionStore
if let userID = sessionStore.session()?.userID {
sessionStore.logOutUserID(userID)
}
twitterButton.setTitle("TWITTER LOGIN", for: .normal)
}
Use below:
[TWTRSessionStore logout]
Deprecated:
[Twitter logOut]
is deprecated.
Users are encouraged to call - [TWTRSessionStore logout] instead of calling this method on the Twitter instance directly.
I am developing a iOS App and I have login with Facebook, LinkedIn, Google+ and Twitter.
All of them let me read my email from my profile using API, EXCEPT Twitter.
Is there any way to get my email?
If not, is there in twitter a "internal email", a generated email like in facebook (someone#facebook.com)?
The reason is that I use email as identifier (primary key) for users in my database.
No, email address are not available via the Twitter API: https://dev.twitter.com/discussions/1737
Nor is there any "internal email" available, you will have to use the twitter username and ask the user fro there e-mail address.
You will have to use Twitter framework. Twitter has provided a beautiful framework for that, you just have to integrate it in your app.
To get user email address, your application should be whitelisted. Here is the link. Go to use this form. You can either send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App etc..They will respond within 2-3 working days.
Here is the story how I got whitelisted by conversation with Twitter support team:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email adress inside your App.
They will review your App and reply to you withing 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
Put your hands on code
Use of Twitter framework:
Get user email address
-(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)
}
}
Get user profile
-(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);
}
}
Hope it helps !!!