0

据我目前了解,一种方法是使用 JSON。但是将 swift 对象发送到服务器以确保服务器具有相同的可用类似乎更好更容易。这样我就可以在每一步中继续使用 swift。

这可能吗?我将如何去做?

当前设置:

  1. 用于发送数据的 Swift Playground。
  2. Kitura 服务器接收数据。

游乐场代码:

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

struct TestObject {
    let foo = "just a string"
    let number = 125
    let array = ["bar", "foo"]

    func printSomeInfo() {
        print(foo + "\(number+25)")
    }
}

func send() {
    let request = NSMutableURLRequest(url: URL(string: "http://192.168.178.80:8090/test")!)
    request.httpMethod = "POST"

    let testObject = TestObject()

    let bodyData = "\(testObject)"
    request.httpBody = bodyData.data(using: String.Encoding.utf8)

    let task =  URLSession.shared.dataTask(with: request as URLRequest,
                                           completionHandler: {
                                            (data, response, error) -> Void in

    })

    task.resume()
}

send()

Kitura main.swift 代码:

import Kitura
import Foundation

let router = Router()

struct TestObject {
    let foo = "just a string"
    let number = 125
    let array = ["bar", "foo"]

    func printSomeInfo() {
        print(foo + "\(number+25)")
    }
}

router.post("/test") {request, response, next in
    response.headers["Content-Type"] = "text/plain; charset=utf-8"

    if let post = try request.readString() {
        // would like to cast to TestObject but that doesn't work
        // let postObject = post as TestObject
        print(post)
    }
}

Kitura.addHTTPServer(onPort: 8090, with: router)
Kitura.run()
4

2 回答 2

1

You would need to serialize the data in some way across the wire. One of the most common way to do this is using JSON. This recent swift blog explains how you can do this. If you need to do this for a lot of different objects, you could abstract out the JSON serialization/deserialization to a common base.

于 2016-10-29T14:00:27.690 回答
0

对于您的情况,有一个很好的 JSON 对象映射库。 https://github.com/Hearst-DD/ObjectMapper 但是,你需要在你的类和结构中添加一些额外的代码来实现它们被映射的能力

于 2016-10-29T12:58:11.257 回答