ios - 可以在 Swift 应用程序和后端之间交换对象吗?

标签 ios json swift server kitura

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

这可能吗?我该怎么做?

当前设置:

  1. Swift playground 发送数据。
  2. Kitura 服务器接收数据。

Playground 代码:

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()

最佳答案

您需要通过网络以某种方式序列化数据。最常见的方法之一是使用 JSON。 This recent swift blog解释了如何做到这一点。如果您需要为很多不同的对象执行此操作,您可以将 JSON 序列化/反序列化抽象为一个公共(public)基础。

关于ios - 可以在 Swift 应用程序和后端之间交换对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318760/

相关文章:

ios - 如何在 Swift 中访问类的类的方法?

objective-c - AVAssetWriterInputPixelBufferAdaptor 和 CMTime

Android sqlite 表到 json 文件

ios - 如何通过代码而不是 Storyboard更改 UIButton 的大小和位置

java - 在 Apache CXF REST 服务中将 JSON 数据作为请求正文提交

java - 读取 Json 文件时出现 libGDX And​​roid SerializationException

ios - 如何在 UIButton 的文本边缘添加额外的空间?

具有目标操作的单元格上的 iOS UIButton,单元格未在 (id)sender 中更新

ios - Xcode 将 iOS 应用归档为 Mac 应用

objective-c - 搜索和替换字符串中的扩展 ASCII