据我目前了解,一种方法是使用 JSON。但是将 swift 对象发送到服务器以确保服务器具有相同的可用类似乎更好更容易。这样我就可以在每一步中继续使用 swift。
这可能吗?我将如何去做?
当前设置:
- 用于发送数据的 Swift Playground。
- 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()