Im currently working throught the App Development with Swift Xcode 10 book from Apple and I have come to the last guided project 'Restaurant App'. Hopefully there are those of you already familiar with the guided app project and can help, and for those not familiar most all the reference code is found in the book chapter 5.6. My guess is I'm not the first to have this problem, but can't find the exact solution. Up to this point I've been able to complete all the lab's and projects to working order and not needed any help from the forums. Everything worked perfectly on this app till it came time to "Submit" the order and call the func submitOrder from the MenuController.swift in where the func will encode the data then set the prepartationTime.prepTime in completion. This issue arises here, I have followed the code line by line and verified there is indeed data. But when trying to unwrap the data and decode it, it returns nil data.
Currently I'm using Xcode 11.5 and Swift 5.2.
Print view output when pressing submit button.
- Call from Order Table to submit the order
OrderTableViewController uploadOrder() menuIDs = [4]
- print data from the submitOrder()
data = ["menuIds": [4]]
jsonData = 15 bytes
request.httpbody = 15 bytes
Submit Order Failed
func submitOrder(forMenuIDs menuIds: [Int], completion: @escaping (Int?) -> Void) {
let orderURL = baseURL.appendingPathComponent("order")
var request = URLRequest(url: orderURL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data: [String: [Int]] = ["menuIds": menuIds]
let jsonEncoder = JSONEncoder()
let jsonData = try? jsonEncoder.encode(data)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let jsonDecoder = JSONDecoder()
if let data = data,
let preparationTime = try? jsonDecoder.decode(PreparationTime.self, from: data) {
print(preparationTime)
completion(preparationTime.prepTime)
}else {
print("Submit Order Failed")
completion(nil)
}
}
task.resume()
}