2014-11-14 49 views
-1

我是新來的斯威夫特,想下面的Objective-C代碼轉換爲斯威夫特:如何在Swift上使用Mashape上的TextAnalysis API?

(顯然,是迅速無unirest庫)。

// These code snippets use an open-source library. http://unirest.io/objective-c 
NSDictionary *headers = @{@"X-Mashape-Key": @"Ia8030aCGGmshlLqLozAf9XERsUQp12ChEhjsnU5MERfwzB07J", @"Content-Type": @"application/x-www-form-urlencoded"}; 
NSDictionary *parameters = @{@"text": @"這是中文分詞測試"}; 
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) { 
    [request setUrl:@"https://textanalysis.p.mashape.com/segmenter"]; 
    [request setHeaders:headers]; 
    [request setParameters:parameters]; 
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) { 
    NSInteger code = response.code; 
    NSDictionary *responseHeaders = response.headers; 
    UNIJsonNode *body = response.body; 
    NSData *rawBody = response.rawBody; 
}]; 

這是Mashape顯示爲預計響應頭:

Connection: keep-alive 
Content-Length: 70 
Content-Type: application/json 
Date: Thu, 13 Nov 2014 11:11:17 GMT 
Server: Mashape/5.0.5 
X-Ratelimit-Requests-Limit: 1000 
X-Ratelimit-Requests-Remaining: 992 

這是Mashape說的是預期的響應正文:

{ 
    "result": "這 是 中文 分詞 測試" 
} 

如何在操場,repl和/或xcode項目中獲得這些結果?

+0

這個網站是不是一個代碼轉換機。你甚至沒有*嘗試*它! – HAS 2014-11-14 17:42:19

+0

我一直在嘗試一個星期。我問了另一個問題,顯示了我的嘗試,但沒有答案,所以我認爲我的方式離基地太遠了。所以我刪除了這個問題,並決定以這種方式提出問題。我想這可能比幫我解決我自己做的可怕嘗試更容易。 – webmagnets 2014-11-14 18:39:50

回答

0

此代碼,通過acmacalister @https://github.com/daltoniam/SwiftHTTP/issues/33提供,爲我工作:

import SwiftHTTP 
    var request = HTTPTask() 
    var params = ["text": "這是中文測試"] //: Dictionary<String,AnyObject> 
    //request.requestSerializer = JSONRequestSerializer() 
    request.requestSerializer.headers["X-Mashape-Key"] = "jhzbBPIPLImsh26lfMU4Inpx7kUPp1lzNbijsncZYowlZdAfAD" 
    request.requestSerializer.headers["Content-Type"] = "application/x-www-form-urlencoded" 
    request.responseSerializer = JSONResponseSerializer() 
    request.POST("https://textanalysis.p.mashape.com/segmenter", parameters: params, success: {(response: HTTPResponse) in if let json: AnyObject = response.responseObject { println("\(json)") } },failure: {(error: NSError, response: HTTPResponse?) in println("\(error)") }) 
相關問題