How to Authorize Twitter with Swifter
Maybe you have found an answer, but I am writing here for those who are still looking for it.
swifter.authorizeWithCallbackURL(NSURL(string: "swifter://success")!, success: {
(accessToken: SwifterCredential.OAuthAccessToken?, response: NSURLResponse) in
println("Access Token key \(accessToken?.key)")
println("userId\(accessToken?.userID)")
println("userName\(accessToken?.screenName)")
println("Access Token secret\(accessToken?.secret)")
//Save the values that you need in NSUserDefaults
},
failure: failureHandler)
You can use any callbackURL
that you like. But for your app to respond to this URL you must do some changes. In the AppDelegate
class add the following. Don't forget to import SwifteriOS
func application(application: UIApplication!, openURL url: NSURL!, sourceApplication: String!, annotation: AnyObject!) -> Bool {
Swifter.handleOpenURL(url)
return true
}
Now click on your project in the Project Explorer, select the info
tab. At the bottom you will see URL Types
. Expand it and click the plus sign. In the URL Schemes
enter your callbackURL
scheme. In this example its swifter
and in identifier
write your app identifier.
Now in any other ViewController
you need to call following before you can call any API that need Authentication.
required init(coder aDecoder: NSCoder) {
var oauthToken : String = NSUserDefaults.standardUserDefaults().valueForKey("oauth_token") as String
var oauthTokenSecret : String = NSUserDefaults.standardUserDefaults().valueForKey("oauth_secret") as String
self.swifter = Swifter(consumerKey: Twitter["consumerKey"]!, consumerSecret: Twitter["consumerSecret"]!, oauthToken: oauthToken, oauthTokenSecret: oauthTokenSecret)
super.init(coder: aDecoder)
}
After this you can send message, post a tweet, create friendship etc.
Access Twitter using Swift
Update 02-03-2015
You need to authenticate with the server using App Only Authentication rather than passing in an OAuth Token.
As well as this, you are also not requesting status' with userId correctly as you are passing in the user's screen name. You need to obtain the user id with the username and then request for status'.
The complete working code is below:
required init(coder aDecoder: NSCoder) {
self.swifter = Swifter(consumerKey: "cKEY", consumerSecret: "cSECRET", appOnly: true)
super.init(coder: aDecoder)
self.swifter.authorizeAppOnlyWithSuccess({ (accessToken, response) -> Void in
self.twitterIsAuthenticated = true
}, failure: { (error) -> Void in
println("Error Authenticating: \(error.localizedDescription)")
})
}
@IBAction func getUserButtonPressed(sender: UIButton?) {
if (self.twitterIsAuthenticated) {
self.getTwitterUserWithName("erhsannounce")
} else {
// Authenticate twitter again.
}
}
func getTwitterUserWithName(userName: String) {
self.swifter.getUsersShowWithScreenName(userName, includeEntities: true, success: { (user) -> Void in
if let userDict = user {
if let userId = userDict["id_str"] {
self.getTwitterStatusWithUserId(userId.string!)
}
}
}, failure: failureHandler)
}
func getTwitterStatusWithUserId(idString: String) {
let failureHandler: ((error: NSError) -> Void) = {
error in
println("Error: \(error.localizedDescription)")
}
self.swifter.getStatusesUserTimelineWithUserID(idString, count: 20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: {
(statuses: [JSONValue]?) in
if statuses != nil {
self.tweets = statuses
}
}, failure: failureHandler)
}
It looks as though you are not Authenticating with the server.
From your code I can see you are using OAuth authentication initialisation but are failing to call the authenticate function.
swifter.authorizeWithCallbackURL(callbackURL, success: {
(accessToken: SwifterCredential.OAuthAccessToken?, response: NSURLResponse) in
// Handle success
},
failure: {
(error: NSError) in
// Handle Failure
})
Add this in and then call your getTwitterTimeline() afterwards.
I hope this helps
Swifter Twitter Set Up
After some more playing around with it, it seems like import SwifteriOS
has been renamed to just import Swifter
. This got rid of any compile errors that I had. I also ended up deleting the Swifter.framework
from all three spots in the photo above with no issues.
I think the docs may be a little bit outdated as well as the example project! Hope this helped someone else!
New Twitter update authentication
So i found the solution. In you app, in the authentication function, your callback url should be something like MyTwitter://success
but in apps.twitter.com you have to make it MyTwitter://
without the second part
How to authenticate using the installed Twitter app
This flow seems to have not been officially supported since the retirement of TwitterKit on May 1, 2018. Any applications that still offer this functionality to their end users likely have some sort of partnership with Twitter to allow for this which is otherwise undocumented publicly.
The reasoning for this was detailed sparsely in a related Twitter Developer Forums thread:
Unfortunately at this time we have had to make some incremental adjustments that are not so smooth for everyone; especially as you’ve found, for mobile app developers. We’re in the middle of a transition to a new API platform (via Twitter Developer Labs) and there will be some changes as we go along - we are asking for your feedback to help us, and if you check the ideas, authentication and authorization is something we’ve heard a lot about.
I cannot tell you today exactly when we’ll get to an enhanced solution, but this is something we are actively working on.
Direct link
The official guidance is to use the traditional WebView method until Twitter officially re-releases this capability:
I don’t believe that this is possible any longer, so I would encourage you to use the full OAuth flow. I apologise that this may not be what your users prefer, but this is the documented way to gain authorisation (we do not document or support URL schemes for the native iOS app).
Direct link
We do not support or document any means of users signing in to Twitter outside of the OAuth flow; any use of undocumented features is subject to change without notice.
Direct link
As linked above Twitter appears to be soliciting feedback on this via their UserVoice page, should you feel so inclined to suggest the re-implementation of such a feature.
Log in with Twitter, now that Twitter Kit is gone
In the list of Twitter libraries you can find that Twitter recommend to use Swifter or you can do OAuth Log in with Twitter authorization using ASWebAuthenticationSession.
Related Topics
Uitableviewcell with Intrinsic Height Based on Width
Could Not Cast Value of Type 'Nsnull' (0X10Aa1B600) to 'Nsstring' (0X10B4Dab48)
iOS Swift Remove Uitableview Cell Separator Space
Table View Controller Duplicate Itself in iOS Swift
Xcode Constraint Break When Switching Between Text Fields Without Dismissing Keyboard
How to Adjust the Uitableviewcell Height to the Content of Uitextview That's Inside
Swift 3 - Loading Multiple Viewcontrollers at Launch
How to Change How a Remote Notification Is Presented Before Presentation
Transfer Gestures on a Uiview to a Uitableview in Swift - iOS
Swift Link Image from Parse Array Using Segues to Secondviewcontroller
Multiple Cells Selected on Scrolling [Reuse Cells Problem]
How to Get Only Keys from Firebase
How to Change a View from Portrait Mode to Landscape Mode and Lock It
How to Get a Substring from a Specific Character to the End of the String in Swift 4