0


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?
}
  • `json.merged(with: json)` Do you want to merge 2 identical `JSON` and set to `self.dataOut`? – Ryan Apr 20 '18 at 19:41
  • It should be `self.dataOut = self.dataOut.merged(with: json)` if I'm understanding your question right. – Ryan Apr 20 '18 at 19:42
  • I'm merging the same json twice to be extra sure that I WILL have the correct json in `self.dataOut`. As far as I'm concerned, `self.dataOut.merged(with:json)` produces exactly the very same result. What I don't understand is why its value changes before and after the `task.resume()` ... Sometimes, an output before the `task.resume()` appears (chronologically) after the an output after ... – Ganamabunta08 Apr 20 '18 at 20:03
  • 1
    You got to print `self.dataOut` inside the block. It is async task. – Ryan Apr 20 '18 at 20:07
  • You might do yourself a favour by dropping `SwiftyJSON` and go with the [`Codable` protocol](https://developer.apple.com/documentation/swift/codable), it is great at turning your random piece of JSON (tm) into some _real_ Swift object. – Patru Apr 21 '18 at 03:00
  • As can be seen in [this question](https://stackoverflow.com/questions/31264172/how-can-i-get-the-data-from-nsurlsession-sharedsession-datataskwithrequest) `task.resume()` just _starts_ the task. It _does not_ wait for completion. You will have to provide some other mechanism to get to know when your task is finished. @Ryan's comment is key to this. – Patru Apr 21 '18 at 03:06
  • @Patru It’s not a great place to discuss about benefit of using SwiftyJSON but the codable still has limitation which can be easily implemented with SwiftyJSON. – Ryan Apr 21 '18 at 04:07
  • @Ryan: You see me blush and you are probably right. I never used `SwiftyJSON` to any extent, but I absolutely admire what `Codable` can do. So I probably do not know what I am talking here. `merge`ing JSON returned from a WebService to an object property looks like a strange idea though. – Patru Apr 21 '18 at 12:28

0 Answers0