iosswifttwitter

Twitter API in SWIFT via Alamofire


I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply can't get it working. My Code looks like:

func TWITTER_getPosts(username:String){
    
        
        let headers = [
            "screen_name": "username",
            "authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
            "include_rts": "false"
        ]
        
        Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
        }
    }

I always end in a

errors = ( { code = 215; message = "Bad Authentication data.";


Solution

  • One of the parameters for the request method is incorrect. If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:

    let headers = [
     "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
     "Accept": "application/json"
    ]
    
    Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
         .responseJSON { response in
             debugPrint(response)
         }
    

    headers: headers should be the way to go.