Я пытаюсь создать приложение для отслеживания пакетов. Изначально свойство «поставляемого» объекта пакета равно нулю, потому что мы еще не получили данные из API. Однако после получения и присвоения значения в вызове API я все еще получаю ноль.
class Item: NSObject {
var name: String?
var carrier: String?
var tracking: String?
var delivered: Bool?
var daysLeft: String?
var date: String?
init (name: String, carrier: String, tracking: String) {
self.name = name
self.carrier = carrier
self.tracking = tracking
}
}
func enterPackage (carrier: String, tracking: String) {
var newItem = Item(name: "some name", carrier: carrier, tracking: tracking)
print(newItem.delivered) //I am getting nil here, as expected because I haven't set it yet
self.loadItem(item: item)
print(newItem.delivered) //Why am I still getting nil here and how do I fix this?
}
func loadItem(item: Item) {
//Perform API request with item carrier and tracking data
//Purposely commented out private API information
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
//Parse JSON and assign values to item
self.parseJSON(data: safeData, item: item)
}
}
task.resume()
}
func parseJSON(data: Data, item: Item) {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(ItemData.self, from: data)
//Results are valid and here is the value assignment
item.delivered = decodedData.status_code == "DE" ? true : false
catch {
print(error)
}
}
Вот файл JSON из запроса API.
{
"tracking_number": "182736488333",
"status_code": "AC",
"status_description": "Accepted",
"carrier_status_code": "OC",
"carrier_status_description": "Shipment information sent to FedEx",
"ship_date": null,
"estimated_delivery_date": "2020-05-04T07:00:00Z",
"actual_delivery_date": null,
"exception_description": null,
"events": [
{
"occurred_at": "2020-04-28T07:52:00Z",
"carrier_occurred_at": "2020-04-28T07:52:00-07:00",
"description": "Shipment information sent to FedEx",
"city_locality": null,
"state_province": null,
"postal_code": "925183100",
"country_code": "US",
"company_name": null,
"signer": null,
"event_code": "OC",
"latitude": null,
"longitude": null
}
]
}