Jeffrey Jeffrey - 1 month ago 14
Swift Question

Possible to exchange objects between Swift app and backend?

As I currently understand it one way to do it is to use JSON. But it would seem better and easier to just send the swift object to the server making sure the server has the same class available. This way I can just keep using swift every step of the way.

Is this possible and how would I go about doing this?

Current setup:


  1. Swift playground to send data.

  2. Kitura server to receive data.



Playground code:

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 code:

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

Answer

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.