我正在使用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)
}
}为此,我得到了以下错误: Error =-6004“数据无法序列化。无法解析Domain=com.alamofire.error响应。序列化过程中未提供错误信息。”UserInfo={NSLocalizedFailureReason=Data无法序列化。无法解析JSON响应。序列化过程中未提供错误信息。}
我读了文档,但它对解决这个问题没有帮助。
发布于 2016-06-01 23:58:25
你似乎在使用某种库?如果是这样,最可能的原因是版本号已更改,您需要对其进行设置。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)
}https://stackoverflow.com/questions/37554664
复制相似问题