-1

我是 Swift 新手,想将以下 Objective-C 代码转换为 Swift:

(显然 swift 没有唯一的库。)

// 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": "这 是 中文 分词 测试"
}

如何在 Playground、repl 和/或 xcode 项目中获得这些结果?

4

1 回答 1

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)") })
于 2014-11-16T22:35:33.473 回答