Twitter Login Integration In iOS Using Swift
Twitter Login Integration In iOS Using Swift
Hi, In this post, we'll learn how to integrate Twitter SDK in iOS apps. Its pretty simple and easy to implement Login using Twitter in iOS applications. You can learn it just by going through this post only once. I hope you'll like it!
FYI, we can use twitter login in 2 ways in our iOS applications. One is using default Twitter Login Button and second one is using our own custom button for twitter login. In this post, I'll guide you through both the twitter login methods.
Without any delay, let's start with our project setup. Again, we'll accomplish our goal by following a step by step approach as mentioned below:
First of all, open your Xcode project and create a single view application. Give some name to your project and click Next.
Here, if you want to use Twitter's own custom Login button then there's no need to add a custom button to your project but If you want to add your own login button then just add it by dragging and dropping a button on your storyboard. Give it some name like "Login With Twitter". Add some constraint on this button and create its action in your ViewController.swift file. After this, close your Xcode project, it's time to move to step number 2.
STEP 2: Install Twitter Pods
Thanks for your time and keep coding.. 👨💻
Hi, In this post, we'll learn how to integrate Twitter SDK in iOS apps. Its pretty simple and easy to implement Login using Twitter in iOS applications. You can learn it just by going through this post only once. I hope you'll like it!
FYI, we can use twitter login in 2 ways in our iOS applications. One is using default Twitter Login Button and second one is using our own custom button for twitter login. In this post, I'll guide you through both the twitter login methods.
Without any delay, let's start with our project setup. Again, we'll accomplish our goal by following a step by step approach as mentioned below:
- Setup Xcode Project
- Install Twitter Pods
- Create App On Twitter Apps Dashboard
- Write Some Code
- Run Our App
First of all, open your Xcode project and create a single view application. Give some name to your project and click Next.
Here, if you want to use Twitter's own custom Login button then there's no need to add a custom button to your project but If you want to add your own login button then just add it by dragging and dropping a button on your storyboard. Give it some name like "Login With Twitter". Add some constraint on this button and create its action in your ViewController.swift file. After this, close your Xcode project, it's time to move to step number 2.
STEP 2: Install Twitter Pods
For installing Twitter pods into your project, fire up the terminal and go to your project directory by giving following command in the terminal:
cd <path of your project>
Example: cd /users/Bhanu/Desktop/Projects/TwitterLoginDemo
Now give one more command
pod init
This command will create a pod file in your project folder. In this file, you need to write:
pod 'TwitterKit'
After saving this, your file will look like this:
Now, run this command in your terminal:
Once all this setup is done, close the terminal and go to your projects folder. Reopen your project and make sure to open .xcworkspace instead of .xcodeproj
STEP 3: Create App On Twitter Apps Dashboard
Here in this step, we'll create our Twitter app on twitter apps dashboard. So, just open your browser and go to this link: Twitter Apps Dashboard
Here just follow the simple steps and register your new app on Twitter's Application Management console. You can follow below mentioned steps to create your new twitter app:
Now, run this command in your terminal:
pod install
This is going to take some time to install the required twitter pods in your project. So, wait for some time. Further, run below command just to ensure that you're using the latest pod versions.
pod update TwitterKit
pod update TwitterKit
Once all this setup is done, close the terminal and go to your projects folder. Reopen your project and make sure to open .xcworkspace instead of .xcodeproj
STEP 3: Create App On Twitter Apps Dashboard
Here in this step, we'll create our Twitter app on twitter apps dashboard. So, just open your browser and go to this link: Twitter Apps Dashboard
Here just follow the simple steps and register your new app on Twitter's Application Management console. You can follow below mentioned steps to create your new twitter app:
- Click on "Create New App"
- Enter Application Details and click on "Create Your Twitter Application"
- Go to permissions tab
- Choose, "Read, write and Access direct messages".
- Check, "Request email address from users"
- Click "Update Settings"
- In your app's setting, don't forget to add "Callback URL", "Privacy Policy URL", "Terms of Service URL". Make sure to use a valid URLs or you can use any placeholder URLs (eg. "http://placeholder.com")
- Update Settings again
- Done.
Now, you'll get the Consumer Key and Consumer Secret Key for your application as shown below:
After creating your app and following all the steps, don't forget to add below provided XML code in your app's info.plist file in the Xcode. For this, just click on your info.plist file and select Open as a Source Code. Now, just after the <dict> tag, insert the following XML snippet into it:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>twitterkit-<consumerKey></string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>twitter</string>
<string>twitterauth</string>
</array>
Here, replace the consumerKey with your own consumer key(Twitter API key) which you get in your Twitter application dashboard for your newly created app.
STEP 4: Write Some Code
Now, open your AppDelegate.swift file and add following line of code in its first application function i.e.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Twitter.sharedInstance().start(withConsumerKey:"gu2dsasdsaTxasObYidfjsfux", consumerSecret:"ZasdasdfhgXcyPP0e5yrjNcsdffjshhabwh23xqlDbhjlfhUdd")
return true
}
Also add one more function here:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return Twitter.sharedInstance().application(app, open: url, options: options)
}
Once all this done, let's jump over to the ViewController.swift file.
Here, we've 2 ways to implement Twitter Login.
1. Using Default Twitter Login Button: This is the simplest way to add twitter login in iOS applications. Just add following lines of code in your viewDidLoad() method:
let logInButton = TWTRLogInButton(logInCompletion: { session, error in
if (session != nil) {
print("signed in as \(String(describing: session?.userName))");
print("userID \(String(describing: session?.userID))");
print("authToken \(String(describing: session?.authToken))");
} else {
print("error: \(String(describing: error?.localizedDescription))");
}
})
logInButton.center = self.view.center
self.view.addSubview(logInButton)
2. Using Custom Login Button: Just add one custom button on your view controller and add following code in your action button's method:
Twitter.sharedInstance().logIn(completion: { (session, error) in
if (session != nil) {
print("signed in as \(String(describing: session?.userName))");
} else {
print("error: \(String(describing: error?.localizedDescription))");
}
})
STEP 5: Run Your App
Once all this done, run your app and you'll get the following screen on your device:
Twitter Login Button Screen |
After successful login, you'll get the user's name, ID, token etc. printed in your console which you can use further as per your own app requirements.
Here’s the full code for your reference:
If you've any doubts or need any further help, then do message me in the comments section below and I'll try to respond you as soon as possible.
Thanks for your time and keep coding.. 👨💻
i got this Error..
ReplyDelete2018-03-09 10:45:38.003170+0530 LocalizationMultiLang[2279:55172] CredStore - performQuery - Error copying matching creds. Error=-25300, query={
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "https://api.twitter.com";
srvr = "api.twitter.com";
sync = syna;
}
2018-03-09 10:45:38.557396+0530 LocalizationMultiLang[2279:53785] [TwitterKit] did encounter error with message "Error obtaining user auth token.": Error Domain=TWTRLogInErrorDomain Code=-1 "
Desktop applications only support the oauth_callback value 'oob'
/oauth/request_token
" UserInfo={NSLocalizedDescription=
Desktop applications only support the oauth_callback value 'oob'
/oauth/request_token
}
error: Optional("Request failed: unauthorized (401)")
Hey Chetan, Sorry for the late response. Was busy with some work and didn't get time to check comments on the post.
DeleteFor the error, It seems you missed something from Step 3, especially the callback URL. Make sure to re consider your steps and follow everything mentioned in step 3 as it is. It will work surely.
Let me know if error comes again.
Thanks
I got the same error, I tried but I don't know where is the problem
ReplyDeleteTweeter Integration[38622:11095394] CredStore - performQuery - Error copying matching creds. Error=-25300, query={
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "https://api.twitter.com";
srvr = "api.twitter.com";
sync = syna;
}
2018-05-05 12:03:29.690434+0530 Tweeter Integration[38622:11095342] [TwitterKit] did encounter error with message "Error obtaining user auth token.": Error Domain=TWTRLogInErrorDomain Code=-1 "
This client application's callback url has been locked
/oauth/request_token
" UserInfo={NSLocalizedDescription=
This client application's callback url has been locked
/oauth/request_token
}
error: Optional("Request failed: unauthorized (401)")
i got a this type of error, i don't know where is the problem
ReplyDeleteClass TWTRAppAuthProvider is implemented in both /Users/ob_apple_5/Library/Developer/CoreSimulator/Devices/B1C47278-75B6-4F90-BF56-E8D14F720A4D/data/Containers/Bundle/Application/498EC413-533B-4B97-B877-35BE417E5F7E/twitterlogin21.app/Frameworks/TwitterKit.framework/TwitterKit (0x10980a548) and /Users/ob_apple_5/Library/Developer/CoreSimulator/Devices/B1C47278-75B6-4F90-BF56-E8D14F720A4D/data/Containers/Bundle/Application/498EC413-533B-4B97-B877-35BE417E5F7E/twitterlogin21.app/Frameworks/TwitterCore.framework/TwitterCore (0x109682370). One of the two will be used. Which one is undefined.
2018-07-06 18:30:54.097841+0530 twitterlogin21[17103:314259] [TwitterKit] did encounter error with message "Error obtaining user auth token.": Error Domain=TWTRLogInErrorDomain Code=-1 "Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings" UserInfo={NSLocalizedDescription=Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings}
error: Optional("Request failed: forbidden (403)")
"_OBJC_CLASS_$_TWTRTwitter", referenced from:
ReplyDeleteerror when use TWTRTwitter.sharedInstance().start(withConsumerKey: "", consumerSecret: "")