Search code examples
iosswiftapitwitteralamofire

Swift twitter search API could not authenticate you response, error


When I call the api for the first time I got the expected response. However, Once I change the params value, the response appears like "message" : "Could not authenticate you:

var params = ["q":"fashion"]

var header = ["authorization":"OAuth 
oauth_consumer_key=\"consumer_key\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1545130242\",oauth_nonce=\"nonce\",oauth_version=\"1.0\",oauth_signature=\"signature\""]

Alamofire.request(url, method: .get, parameters: params,headers: headers).responseJSON { (response) in
        if (response.result.isSuccess){
            print("Success! got the weather data")
            let twitterJSON: JSON = JSON(response.result.value!)
            // self.updateWeatherData(json: weatherJSON)
            print("\(twitterJSON)")
            self.updateTwittes(json: twitterJSON)
        }else{
            print("Error \(String(describing: response.result.error)) ")
        }
    }

Solution

  • The TwitterAPI request should be called using BrearerToken which can be obtained by curl command:

            let params = ["query":"\(searchText) lang:en","maxResults":"10"]
            let headers = ["authorization":"bearer <BrearerToken>","content-type":"application/json"]
            getTwitterData(url: url,headers: headers ,Params: params)
    
    func getTwitterData(url: String,headers: [String:String] ,Params: [String: String]){
    
    
        Alamofire.request(url, method: .post, parameters: Params,encoding:JSONEncoding.default,headers: headers).responseJSON { (response) in
            if (response.result.isSuccess){
                print("Success! got the twitter data")
                let twitterJSON: JSON = JSON(response.result.value!)
    
                print("\(twitterJSON)")
                self.updateTwittes(json: twitterJSON)
            }else{
                print("Error \(String(describing: response.result.error)) ")
            }
        }
    }