URLSession

How to pull data from remote server and show them on another viewcontroller ie. Profile View Controller

here's my code

    let url = URL(string: stringURL)
    guard let requestUrl = url else { fatalError() }
     
    // Prepare URL Request Object
    var request = URLRequest(url: requestUrl)
    request.httpMethod = "POST"
     
    // Set HTTP Request header
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("1088", forHTTPHeaderField: "Content-Length")
     
    // HTTP Parameters which will be sent in HTTP Request body
    let postString = "userID=\(useridTextField.text ?? "")&password=\(passwordTextField.text ?? "")"
     
    // Set HTTP Request Body
    request.httpBody = postString.data(using: String.Encoding.utf8)
     
    // Perform HTTP Request
    let session = URLSession.shared
    let task = session.dataTask(with: request) { data, response, error in
       
      guard let data = data else {
        return
      }

      do {
        var user = try JSONDecoder().decode(User.self, from: data)
        user.idNumber = self.idNumber
        user.firstName = self.firstName
        user.middleName = self.middleName
        user.lastName = self.lastName
        user.emailAddress = self.emailAddress
        user.mobileNumber = self.mobileNumber
        user.landline = self.landline
   
         
        return
      } catch {
        let str = String(decoding: data, as: UTF8.self)
        print(str)
         
      }
     
    }
    task.resume()

here's the code from Profile Viewcontroller

  @IBOutlet weak var idNumberLabel: UILabel!
  @IBOutlet weak var emailAddressLabel: UILabel!
  @IBOutlet weak var mobileNumberLabel: UILabel!
   
  var idNumber: String = ""
  var firstName: String = ""
  var lastName: String = ""
  var emailAddress: String = ""
  var mobileNumber: String = ""
   
  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    nameTextLabel.text = firstName

here is the simulator

As you show only parts of code, it is impossible to understand how they are linked. Where do you call the url ?

Note: when you copy screen, please reduce the size of the image. In addition, it does not provide any useful information for the question asked.

A few notes here just based on what I see. First, you will want to check for errors first in your dataTask completion handler, along with checking to make sure that you have a 200 response. A very basic example of this can be found here :

if let error = error {
    self.handleClientError(error)
    return
}
guard let httpResponse = response as? HTTPURLResponse,
    (200...299).contains(httpResponse.statusCode) else {
    self.handleServerError(response)
    return
}
if let mimeType = httpResponse.mimeType, mimeType == "text/html",
    let data = data,
    // Send your data off here to be processed.
}

Next, once you app has the data, send it to the appropriate model layer to be parsed. This could be based on the model layer that corresponds to your view, or just a generic model object in your project. The benefit here is that your network stack does not parse the JSON data, and your view can have a concrete object to work with. Lastly, after your model object is parsed, sent it to your view so that your view can display the corresponding data in the UI.

From a general networking standpoint, I like to have a network stack that is as generic as possible. For example, one method that makes a GET and POST request and then just forwards that data to be parsed to the model layer.

Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
URLSession
 
 
Q