I am able to access the Watson Tone Analyzer API from a web page using the following code written in PHP using CURL:
$username='long-user-name';
$password='my-password';
$data = json_encode(array('text' => 'All you need is love'));
$URL = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
IBM/Watson does not provide sample code for accessing API through Swift or AlamoFire for IOS although their Swift SDK apparently uses AlamoFire. I am not downloading their SDK because it requires carthage and has other dependencies that people report as causing problems. However, you are supposed to be able to request the API using AlamoFire.
The following code that I tried gives a 401 error for bad authentication. Can anyone from the IBM Bluemix team or elsewhere suggest how to convert the above working curl to a valid AlamoFire request? Thanks in advance for any suggestions.
My code that returns 401 for bad authentication:
func postToWatson () {
print("post to watson called")
let url: String = "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19"
let message = "All you need is love"
var parameters = [
"username":"my-username",
"password":"my-password"]
parameters["text"] = message
Alamofire.request(url, parameters: parameters)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.result)
}
}