Я пытаюсь создать приложение для отслеживания посылок. Изначально свойство «доставлено» объекта пакета равно нулю, поскольку мы еще не получили данные от 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)
}
}
< /code>
Вот файл JSON из запроса API. < /p>
{
"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
}
]
}
Подробнее здесь: https://stackoverflow.com/questions/615 ... pi-request
Почему моя переменная по-прежнему равна нулю после присвоения через запрос API? ⇐ IOS
Программируем под IOS
1737822675
Anonymous
Я пытаюсь создать приложение для отслеживания посылок. Изначально свойство «доставлено» объекта пакета равно нулю, поскольку мы еще не получили данные от 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)
}
}
< /code>
Вот файл JSON из запроса API. < /p>
{
"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
}
]
}
Подробнее здесь: [url]https://stackoverflow.com/questions/61553989/why-is-my-variable-still-nil-after-assignment-via-api-request[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия