正如我目前所理解的那样,一种方法是使用JSON。但是将swift对象发送到服务器并确保服务器具有相同的可用类似乎更好更容易。通过这种方式,我可以继续使用swift的每一步。
这可能吗?我将如何做到这一点?
当前设置:
游乐场代码:
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()
答案 0 :(得分:1)
您需要通过网络以某种方式序列化数据。最常见的方法之一是使用JSON。 This recent swift blog解释了如何做到这一点。如果您需要为许多不同的对象执行此操作,则可以将JSON序列化/反序列化抽象为公共库。
答案 1 :(得分:0)
根据您的情况,有一个很好的JSON对象映射库。 https://github.com/Hearst-DD/ObjectMapper 但是,您需要在类和结构中使用一些额外的代码来实现它们的映射功能