2016-05-31 83 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文檔傾向於擁有您可以使用的示例。 –