-1

I am new to Swift and would like to convert the following Objective-C code to Swift:

(Obviously there is no unirest library for 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;
}];

This is what Mashape shows as the expected response headers:

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

This is what Mashape says is the the expected response body:

{
  "result": "这 是 中文 分词 测试"
}

How can I get these results in the playground, repl, and/or an xcode project?

webmagnets
  • 2,266
  • 3
  • 33
  • 60
  • This site is not a code conversion machine. You have not even *tried* it! – HAS Nov 14 '14 at 17:42
  • I have been trying for a week. I asked another question showing what I tried, but there were no answers so I assumed I was just way too far off base. So I deleted that question and decided to ask it this way. I figured it might be easier to help me this way than fixing my horrible attempt to do it myself. – webmagnets Nov 14 '14 at 18:39

1 Answers1

0

This code, provided by acmacalister @ https://github.com/daltoniam/SwiftHTTP/issues/33, worked for me:

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)") })
webmagnets
  • 2,266
  • 3
  • 33
  • 60