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
Implementing Single-User OAuth on Twitter using Swift
After hours of digging, I found a package which can expedite the process. It is called Swifter. You can also download the package using Cocoapods by adding pod "Swifter", :git => "https://github.com/mattdonnelly/Swifter.git"
After downloading, add import Swifter
at the top of your class file.
Instantiate Swifter by adding the following,
let twitter = Swifter(consumerKey: "", consumerSecret: "", oauthToken: "", oauthTokenSecret: "")
The oauthToken
and oauthTokenSecret
can be found in your app.twitter.com page. They are your Access Token and Access Token Secret respectively. IF you don't have the access token yet, create one at the Keys and Tokens page. If you want to tweet from your own account, you need to provide the access token to allow single-user OAuth to perform actions like posting tweets.
If you want to trigger a tweet update, just add the following in your button action closure or sort,
twitter.postTweet(status: "Hello world",success: { status in
print("successfully tweeted! \(status.description)")
}, failure: { error in
print("error tweeting! \(error)")
})
Do note that I am using Swifter 2.1.0.
Getting Twitter user details using swift
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!
Swift open twitter profile with action button
Adding this command in to info.plist you can solve this problem.
LSApplicationQueriesSchemes
How do I store & access a Twitter Fabric login session (iOS/Swift)?
If there is currently an active session you should be able to access it just like the docs say to
Twitter.sharedInstance().session()
If the user isn't logged in that method will return nil. If you want to know if someone is already authenticated just check to see if that method returns a value or not.
Related Topics
How to Run App in Simulator Xcode 6
Declaring Conformance to @Objc Protocol in Empty Extension Breaks with Exc_Bad_Instruction
Could Not Cast Value of Type Uiview to [Customview] Using Xib
Swift Format Text Field When User Is Typing
Is There a Neat Way to Represent a Fraction as an Attributed String
How to Make a Variable from a String
Updating Switfui View When Coredata Changes
Swift - Pass JSON Data to Other Views
What Does Cloning a Github Repository Mean
Swift Switch Char{ Case "\U{E2}:
Swift Cannot Output When Using Nstimer
Swiftui - Navigation View Opening with Back Button and Half Grey Screen/Weird Behavior
Change Mkmarkerannotationview Size
Firestore Security Rules Breaking with Update Rule
Swift 3 Errors with Additional Data
Core Data Update in Swift While Selecting Any Row in List Table View Not Working