我正在使用Swift使用IBM Watson Tone Analyzer API。我尝试了以下代码:
override func viewDidLoad()
{
print("hello")
super.viewDidLoad()
let username = "USERNAME"
let password = "PASSWORD"
let versionDate = "2016-05-19" // use today's date for the most recent version
let service = ToneAnalyzer(username: username, password: password, version: versionDate)
let failure = { (error: NSError) in print(error) }
service.getTone("Text that you want to get the tone of", failure: failure) { responseTone in
print(responseTone.documentTone)
}
}
为此,我收到以下错误: 错误域= com.alamofire.error代码= -6004"数据无法序列化。无法解析JSON响应。序列化期间未提供错误信息。" UserInfo = {NSLocalizedFailureReason =数据无法序列化。无法解析JSON响应。序列化期间未提供错误信息。}
我阅读了文档,但它没有帮助解决这个问题。
答案 0 :(得分:1)
您似乎在使用某种图书馆?如果是这样,最可能的原因是版本号已更改,您需要设置它。 More details about that here。
以下是我所做的一些示例代码(原谅我,我的Swift知识非常基本)。
//: Playground - noun: a place where people can play
import UIKit
var username = "<SERVICE USERNAME HERE>"
var password = "<SERVICE PASSWORD HERE>"
var endpoint = "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19&text="
var sampleText = "I am really excited to be working with Watson!"
// -------------------------------------------------------------------
var authString = username + ":" + password
var authData = authString.dataUsingEncoding(NSASCIIStringEncoding)
var authValue = "Basic " + authData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
var toneUrl = endpoint + sampleText.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let url = NSURL(string: toneUrl)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Authorization" : authValue]
let session = NSURLSession(configuration: config)
var taskIsRunning = true;
let task = session.dataTaskWithURL(url!) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
// Work with JSON object.
}
catch {
print("Problem serialising JSON object")
}
}
taskIsRunning = false
}
task.resume()
while (taskIsRunning) {
sleep(1)
}