2016-05-31 50 views
3

我正在使用Swift使用IBM Watson Tone Analyzer API。我尝试下面的代码:使用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响应。在序列化过程中没有提供错误信息。}

我阅读文档,但没有帮助解决此问题。

回答

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) 
} 
+0

太棒了!请让我知道你是怎么做的(文档/视频)?我同样尝试使用Personality Insights和其他API – user2609410

+0

我在沃森集团工作。你会发现上面的代码应该适用于任何其他服务(GET调用)并稍加修改。相关服务API文档倾向于拥有您可以使用的示例。 –