I'm doing a ServerTransport class and I'm running into a bit of a problem ...
Long story short, I want a ServerTransport object to be able to get and/or post data at self.link.
The class member self.dataOut is supposed to hold whatever is coming from the server.
The method receive() should create the request and put everything into dataOut.
I'm using SwiftyJSON and I learned about the merged(with:) method.
I had hoped to create a temporary constant called json, and deep copy it into self.dataOut. Just to be extra sure, I merged json with itself.
No such luck. Whenever the json constant goes out of scope, the self.dataOut member becomes JSON() once again.
Am I doing something wrong? Is what I intend to do even possible? Below is my code.
Thanks in advance.
class ServerTransport {
var dataIn: Data?
var dataOut : JSON
var link: String
var responseType : String
init(_ link : String, _ responseType : String = "application/json", _ dataIn : Data? = nil) {
self.dataIn = dataIn
self.link = link
self.responseType = responseType
self.dataOut = JSON()
}
func receive() {
var request = URLRequest(url: URL(string: self.link)!)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error : \(error)")
return
}
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
return
}
if let mimeType = response.mimeType, mimeType == self.responseType, let data = data{
guard let json = try? JSON(data : data) else {
return
}
do {
self.dataOut = try json.merged(with: json)
}catch {
print("exception")
// nothing let's just hope that we won't ever reach this point
}
}
print(self.dataOut) // Correct data from server
}
task.resume()
print(self.dataOut) // Empty JSON ... Is it because the json variable is out of scope ?
// Wasn't merge supposed to give a deep copy of json?
}