Reputation: 909
I have the following code in a view controller class:
import UIKit
class orderStatusVC: UIViewController {
//================ Segue Initializers ================//
var orderNumber: String = ""
//================ Member Variables ================//
var orderStatusTitle: String = ""
var orderStatusDesc: String = ""
//================ Object Outlets ================//
@IBOutlet weak var orderStatusLabel: UILabel!
@IBOutlet weak var orderStatusText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
//Call the function to pull the JSON data
getData()
}
func getData() {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: "http://www.mywebsite.com/checkOrderStatus.php") else {return}
let request = NSMutableURLRequest(url: URL)
request.httpMethod = "POST"
// Headers
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
//This is the data that is sent to the server-side script, which contains a string (a 19-digit order number)
let bodyObject: [String: String] = [
"orderNumber":"\(orderNumber)" as String
]
request.httpBody = try! JSONSerialization.data(withJSONObject: bodyObject, options: [])
//This code handles the response from the server-side script
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
guard error == nil else {
print("error calling GET")
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let orderStatus = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
//These two lines assign the returned JSON Data to the previously declared variables under the "Member Variables" heading.
self.orderStatusTitle = orderStatus["orderStatus"]?["statusTitle"] as! String
self.orderStatusDesc = orderStatus["orderStatus"]?["statusDesc"] as! String
/* ============================================
If I uncomment these next two lines,
it accurately displays the correct data
in the log.
============================================ */
//print(orderStatus["orderStatus"]?["statusTitle"])
//print(orderStatus["orderStatus"]?["statusDesc"])
/* ============================================
However, the following two lines do NOT succeed
at putting the returned JSON values into the
designated outlets
============================================ */
self.orderStatusLabel.text = self.orderStatusTitle
self.orderStatusText.text = self.orderStatusDesc
return
} catch {
print("Error trying to convert data to JSON")
return
}
})
task.resume()
session.finishTasksAndInvalidate()
return
}
}
This code does not produce an errors, however, when I run the script, it also does not populate the label/textview with the correct data. In fact - it doesn't show anything at all.
I had toyed around with trying to put the "getData()" function call in the viewWillAppear method, but that didn't get me anywhere either.
I am running a similar script in another one of my apps, and it seems to work just fine - except I am using the returned text in an alert controller rather than a label - so I can't quite figure out why this is failing.
Does anybody have any ideas?
Upvotes: 0
Views: 797
Reputation: 1021
You're trying to update de UI in a background thread. You should try to do the following
OperationQueue.main.addOperation {
self.orderStatusLabel.text = self.orderStatusTitle
self.orderStatusText.text = self.orderStatusDesc
}
Also, the following line is not necessary:
session.finishTasksAndInvalidate()
Upvotes: 1