Недавно я применил нумерацию страниц к моему табличному виду, чтобы продолжить загрузку данных при прокрутке. Я могу заставить все работать, как и ожидалось, при первоначальной загрузке, однако, когда я пытаюсь изменить свой идентификатор платформы, я очищаю свой массив и пытаюсь перезагрузить его с новыми данными так же, как я делал в viewDidLoad, но на этот раз при сбое им произойдет ошибка Индекс вне диапазона. Почему массив не пополняется в методе pickerView, как в viewDidLoad? Заранее благодарю за любую помощь, которую вы можете предоставить.
Мой код приведен ниже, я считаю, что это все необходимые здесь методы
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.platformPicker.delegate = self
self.platformPicker.dataSource = self
games.removeAll()
pickerData = ["NES", "SNES", "Nintendo 64", "Gamecube", "Game Boy", "Gameboy Advance", "Sega Genesis", "Sega CD"]
downloadJSON(platformSelected: "18", gameName: nil, offset: nil) {
self.setPlatformIcon()
self.tableviewPlatformImage.image = UIImage(named: "\(self.imageName)")
self.tableView.reloadData()
}
tableView.delegate = self
tableView.dataSource = self
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
загрузка JSON
func downloadJSON(platformSelected: String?, gameName: String?, offset: String?, completed: u/escaping () -> () ) {
let fields = "age_ratings.rating, age_ratings.category, genres.name, cover.image_id, name, first_release_date, summary, involved_companies.company.name, total_rating, platforms.category, platforms, cover.id, popularity, platforms.versions.platform_logo.image_id, platforms.platform_logo.image_id, platforms.platform_logo.url, screenshots.image_id"
let gameCategory = "1"
let limit = "100"
let sortField = "name"
currentPlatform = platformSelected
currentGame = gameName
if gameName != nil {
searchString = "\"\(gameName!)\""
print(searchString!)
}
var parameters = ""
if platformSelected != nil { if currentOffset == nil {
parameters = "fields \(fields);\nlimit \(limit);\noffset 0;\nwhere platforms = \(platformSelected!);\nsort \(sortField) asc;"
} else {parameters = "fields \(fields);\nlimit \(limit);\noffset \(currentOffset);\nwhere platforms = \(platformSelected!);\nsort \(sortField) asc;" }
} else if gameName != nil {
parameters = "fields \(fields);\nlimit \(limit);\nsearch \(searchString!);\noffset \(offset);"}
let postData = parameters.data(using: .utf8)
print("\(platformSelected)"
let url = URL(string: "https://api-v3.igdb.com/games/")!
let apiKey = "MY API KEY"
var requestHeader = URLRequest.init(url: url )
requestHeader.httpBody = postData
requestHeader.httpMethod = "POST"
requestHeader.setValue(apiKey, forHTTPHeaderField: "user-key")
requestHeader.setValue("application/json", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: requestHeader) { (data, response, error) in
if error == nil {
do {
let json = String(data: data!, encoding: .utf8)
print("\(json)")
let decodedJSON = try JSONDecoder().decode([Game]?.self, from: data!)
if let parseJSON = decodedJSON {
var items = self.games
items.append(contentsOf: parseJSON)
if self.initialOffset < items.count {
self.games = items
self.initialOffset = items.count
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
DispatchQueue.main.async {
completed()
}
} catch {
print(error)
}
}
}.resume()
}
pickerView didSelectRow
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("\(row), \(component)")
switch row {
case 0:
//NES
picked = 18
gdbPlatformID = 7
case 1:
//SNES
picked = 19
gdbPlatformID = 6
case 2:
//N64
picked = 4
gdbPlatformID = 3
case 3:
//GC
picked = 21
gdbPlatformID = 2
case 4:
//GB
picked = 33
gdbPlatformID = 4
case 5:
//GBA
picked = 24
gdbPlatformID = 5
case 6:
//SG
picked = 29
gdbPlatformID = 18
case 7:
//SCD
picked = 78
gdbPlatformID = 21
default:
print("invalid selection")
}
self.games.removeAll()
downloadJSON(platformSelected: "\(picked)", gameName: nil, offset: "\(initialOffset)") {
self.setPlatformIcon()
self.tableviewPlatformImage.image = UIImage(named: "\(self.imageName)")
self.tableView.reloadData()
}
}
setPlatformIcon
func setPlatformIcon() {
//application crashes on the next line, self.games is empty if i print it to the console here.
switch self.games[0].platforms![0].id {
case 18:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "NESLogo"
} else {
//Dark Mode
self.imageName = "NESLogoInverse"
}
case 19:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "SNESLogo1"
} else {
//Dark Mode
self.imageName = "SNESLogo1Inverse"
}
case 4:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "N64Logo"
} else {
//Dark Mode
self.imageName = "N64LogoInverse"
}
case 21:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "GCLogo"
} else {
//Dark Mode
self.imageName = "GCLogoInverse"
}
case 33:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "GBLogo"
} else {
//Dark Mode
self.imageName = "GBLogoInverse"
}
case 24:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "GBALogo"
} else {
//Dark Mode
self.imageName = "gbaLogoInverse"
}
case 29:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "SegaGenesisLogo"
} else {
//Dark Mode
self.imageName = "SegaGenesisLogoInverse"
}
case 78:
if self.traitCollection.userInterfaceStyle == .light {
//Light Mode
self.imageName = "SegaCDLogo"
} else {
//Dark Mode
self.imageName = "SegaCDLogoInverse"
}
default:
print("Invalid Platform")
}
}