Roman Romanenko
Roman Romanenko

Reputation: 766

How to get Twitter access token with Alamofire (Swift 2.2)

I'm only can authorize with Fabric and get userID and userName. But I need to get "accessToken". I try send simple request something like this:

Alamofire.request(.GET, "https://api.twitter.com/1.1
/oauth2/token")
         .responseJSON { response in
             print(response)
         }

But I wasn't successful(

And one more... How to right pass on ConsumerKey and ConsumerSecret as parametr?

Upvotes: 2

Views: 817

Answers (1)

Roman Romanenko
Roman Romanenko

Reputation: 766

Here is the answer maybe it help someone:

let consumerKey = "yourConsumerKey"
let consumerSecret = "yourConsumerSecret"
let credentialsString = "\(consumerKey):\(consumerSecret)"
let credentialsData = (credentialsString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = credentialsData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let headers = ["Authorization": "Basic \(base64String)", "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"]
let params: [String : AnyObject] = ["grant_type": "client_credentials"]

Alamofire.request(.POST, "https://api.twitter.com/oauth2/token", headers: headers, parameters: params)
     .responseJSON { response in switch response.result {
         case .Success(let JSON):

            let response = JSON as! NSDictionary
            let userModel = response

            print("----------------")
            print("")
            print("userModel from TW")
            print(userModel)
            print("")
            print("----------------")

         case .Failure(let error):

            print("Request failed with error: \(error)")

            }
}

Upvotes: 2

Related Questions