如何解决实现分页后,即时通讯在滚动tableview时出现UIImage问题
当前有一个tableview,在每个单元格中包含不同的图像,然后从URL中下载图像,该URL是从JSON获得的,并将其作为imageviews图像。我的问题是,在我进行分页呼叫后,我刚刚滚动过去的图像变成了单个图像并粘贴,并且只有新分页的信息才显示正确的信息。
通过JSON给出数据的方式,大多数数据包含在一个对象数组中,该对象数组包含除图像之外的大多数信息。图像是在字典中单独给出的,该字典采用对象ID并将其匹配,然后提供适当对象的图像URL。我在Networking类中实现了分页,在该类中,我正在进行JSON下载调用:
func downloadGamesByPlatformIDJSON(platformID: Int?,fields: String?,include: String?,pageURL: String?,completed: @escaping () -> () ) {
var urlString : String?
if pageURL == nil {
urlString = "https://api.thegamesdb.net/v1/Games/ByPlatformID?apikey=\(apiKey)&id=\(platformID!)"
if fields != nil {
urlString = urlString! + "&fields=" + fields!
}
if include != nil {
urlString = urlString! + "&include=" + include!
}
} else {
urlString = pageURL!
}
print(urlString!)
let url = URL(string: "\(urlString!)")!
print(url)
var requestHeader = URLRequest.init(url: url)
requestHeader.httpMethod = "GET"
requestHeader.setValue("application/json",forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: requestHeader) { (data,response,error) in
if error != nil {
print("error = \(error)")
completed()
}
if error == nil {
do {
print("error = nil")
let json = String(data: data!,encoding: .utf8)
print(json)
if let jsonDecodedPlatforms = try JSONDecoder().decode(ByPlatformIDData?.self,from: data!) {
print(jsonDecodedPlatforms)
let decodedJSON = jsonDecodedPlatforms.data?.games
self.boxart = jsonDecodedPlatforms.include.boxart
self.baseURL = jsonDecodedPlatforms.include.boxart.baseURL
self.page = jsonDecodedPlatforms.pages
if let parseJSON = decodedJSON {
var items = self.games
var boxarts = self.imageArray
items.append(contentsOf: parseJSON)
if self.initialOffset < items.count {
self.games = items
self.imageArray = boxarts
self.initialOffset = items.count
} else {
self.games = items
self.imageArray = boxarts
}
}
}
DispatchQueue.main.async {
completed()
print(data)
}
} catch {
print(error)
}
}
}.resume()
}
}
因此,即时通讯正在做的是,如果即时通讯在最后一个单元格上,我将下载下一页数据并将其附加到对象数组中。这似乎工作得很好,但是图像只是一次下载到单元中,它们存放在一系列单独的对象中。香港专业教育学院进行了几次尝试来获取下载的图像,将其附加到图像数组,将indexPath.row处的图像应用于imageview,然后以与处理其余信息相同的方式对其进行处理。这导致崩溃,因为它找不到除第一个索引之外的任何索引。我把头发拔了。我错过了什么?任何帮助表示赞赏。
这是我的其他关联代码:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath) as! ViewControllerTableViewCell
if indexPath.row == (network.games.count - 1) && network.page?.next != nil {
pageURL = network.page?.next
network.downloadGamesByPlatformIDJSON(platformID: nil,fields: nil,include: nil,pageURL: network.page?.next) {
print("pagination successful")
tableView.reloadData()
}
}
if frontImageName != nil {
cell.tableViewCoverImage.loadImage(from: imageUrl) { print("tableViewCoverImage loaded!")
self.network.imageArray.append(cell.tableViewCoverImage.image)
self.coverImage = cell.tableViewCoverImage.image!
cell.tableViewCoverImage.image = self.network.imageArray[indexPath.row]
}
}
else {
cell.tableViewCoverImage.image = UIImage(named: "noArtNES")
}
return cell
}
extension UIImageView {
func loadImage(from url: String,completed: @escaping () -> ()) {
let imageURL = URL(string: url)
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: imageURL!) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
completed()
}
}
}
}
}
{
"code": 200,"status": "Success","data": {
"count": 20,"games": [
{
"id": 4,"game_title": "Star Fox 64","release_date": "1997-06-30","platform": 3,"players": 4,"overview": "The Lylat system has been invaded! Join Fox McCloud and his Star Fox team as they fight to save the galaxy from the clutches of the evil Andross. Travel to many different 3-D worlds. Battle the enemy in the air and on the ground and listen in as Fox McCloud interacts with a cast of characters.\r\n\r\nSee how it feels to feel what you see! The N64 Rumble Pak controller accessory instantly transmits all the bumps and blasts during the action. It’s a new jolt to your game play experience!\r\n\r\n* Four Players compete simultaneously in Vs. mode!\r\n* Game Pak memory saves the top 10 scores!\r\n* Outstanding cinema scenes tell the Star Fox saga!","last_updated": "2018-08-11 15:01:11","rating": "E - Everyone","coop": "No","youtube": "jsEcmfPwnHo","os": null,"processor": null,"ram": null,"hdd": null,"video": null,"sound": null,"developers": [
6037
],"genres": [
1,8
],"publishers": [
3
],"alternates": [
"Lylat Wars"
]
},{
"id": 42,"game_title": "Mario Party","release_date": "1999-02-08","overview": "Every game in the main series has a standard Party Mode in which up to four players play through a board,trying to collect as many stars as possible. In every turn,each player rolls a die and progresses on the board,which usually has branching paths. Coins are primarily earned by performing well in a minigame played at the end of each turn. On most boards,players earn stars by reaching a star space and purchasing a star for a certain amount of coins. The star space appears randomly on one of several pre-determined locations and moves every time a star is purchased,usually occupying a blue space.\r\nEvery Mario Party contains at least 50 to almost 110 minigames with a few different types. Four-player games are a free-for-all in which players compete individually. In 2-on-2 and 1-on-3 minigames,players compete as two groups,cooperating to win,even though they are still competing individually in the main game. Some minigames in Mario Party are 4-player co-op,even though it doesn't say it. In most situations,winners earn ten coins each.","last_updated": "2018-07-11 21:05:01","youtube": "sScj7MwjHBs","developers": [
3923
],2,6,11
],"alternates": null
},{
"id": 68,"game_title": "Turok: Dinosaur Hunter","release_date": "1997-03-04","players": 1,"overview": "Much like your usual 1st person shooter,although with dinosaurs as your main enemy. Includes 14 high tech weapons,like the Quad Rocket Launcher and the Atomic Fusion Cannon. You control Turok,who must take on the Campaigner and his highly evolved dino's. The objective is to collect pieces of the Chronoscepter,which is the only weapon that can help to destory the Campaigner,and to stop him from using the power of the weapon to destory the Lost Land.","last_updated": "2020-04-16 11:18:30","rating": "M - Mature 17+","youtube": "3AKbul3ILM0","developers": [
4065
],"genres": [
8
],"publishers": [
28
],{
"id": 216,"game_title": "Super Mario 64","release_date": "1996-09-29","overview": "Mario is super in a whole new way! Combining the finest 3-D graphics ever developed for a video game and an explosive sound track,Super Mario 64 becomes a new standard for video games. It's packed with bruising battles,daunting obstacle courses and underwater adventures. Retrieve the Power Stars from their hidden locations and confront your arch nemesis - Bowser,King of the Koopas!","last_updated": "2020-07-09 20:19:39","youtube": "cx78guiPMP8","developers": [
6043
],15
],{
"id": 239,"game_title": "A Bug's Life","release_date": "1998-11-06","overview": "As hopeful hero Flik,you're the colony's last chance against the seed-grubbing grasshoppers. Run,fly,kick,squish,and slide through 15 challenging levels of 3-D animated gameplay. Outmaneuver 13 types of enemies,including The Bird and her deadly beak. Then,throw your weight around with tough antics like the Berry Attack and the Butt-Bounce. Because on this ride,you'll need more than just high hopes.\r\n\r\n• Search for power-ups,tokens and objects to use in the \"Living World.\"\r\n• Get a bug's-eye-view of a magical 3-D world.\r\n• Swing,slide and navigate Flik through immense bug-infested levels.","youtube": "j0ITQ9h2o4c","developers": [
2383
],"genres": [
2
],"publishers": [
33
],{
"id": 240,"game_title": "Army Men: Sarge's Heroes","release_date": "2000-11-16","overview": "CONFIDENTIAL. 0600 hours: Tan forces captured Bravo Company Commandos. General Plastro has new weapons of mass destruction: magnifying glass,M-80 firecrackers and the garbage disposal. This is a job for Sarge. Requisition M-60s,shotguns,bazookas,flame throwers,grenades,sniper rifles,mortars,mine sweepers and plenty of ammo. Good luck,soldier.","last_updated": "2020-02-17 06:17:04","rating": "T - Teen","youtube": "V5IbVO1MUbc","developers": [
77
],"publishers": [
63
],"alternates": null
}
]
},"include": {
"boxart": {
"base_url": {
"original": "https://cdn.thegamesdb.net/images/original/","small": "https://cdn.thegamesdb.net/images/small/","thumb": "https://cdn.thegamesdb.net/images/thumb/","cropped_center_thumb": "https://cdn.thegamesdb.net/images/cropped_center_thumb/","medium": "https://cdn.thegamesdb.net/images/medium/","large": "https://cdn.thegamesdb.net/images/large/"
},"data": {
"4": [
{
"id": 846,"type": "boxart","side": "front","filename": "boxart/front/4-1.jpg","resolution": "1000x705"
},{
"id": 847,"side": "back","filename": "boxart/back/4-1.jpg","resolution": "1000x705"
}
],"42": [
{
"id": 581,"filename": "boxart/back/42-1.jpg","resolution": "1000x693"
},{
"id": 215518,"filename": "boxart/front/42-1.jpg","resolution": null
}
],"68": [
{
"id": 864,"filename": "boxart/front/68-1.jpg","resolution": "1000x691"
},{
"id": 865,"filename": "boxart/back/68-1.jpg","resolution": "1000x694"
}
],"141": [
{
"id": 7164,"filename": "boxart/front/141-1.jpg","resolution": "2100x1532"
},{
"id": 7165,"filename": "boxart/back/141-1.jpg","resolution": "2100x1532"
}
],"160": [
{
"id": 28559,"filename": "boxart/front/160-1.jpg","resolution": "1000x688"
},{
"id": 28560,"filename": "boxart/back/160-1.jpg","161": [
{
"id": 894,"filename": "boxart/back/161-1.jpg","resolution": "1000x697"
},{
"id": 83199,"filename": "boxart/front/161-1.jpg","resolution": "1050x768"
}
],"162": [
{
"id": 517,"filename": "boxart/back/162-1.jpg","resolution": "1000x686"
},{
"id": 111271,"filename": "boxart/front/162-1.jpg","resolution": "2100x1536"
}
],"173": [
{
"id": 7353,"filename": "boxart/front/173-1.jpg",{
"id": 7354,"filename": "boxart/back/173-1.jpg","175": [
{
"id": 7469,"filename": "boxart/front/175-1.jpg",{
"id": 7470,"filename": "boxart/back/175-1.jpg","176": [
{
"id": 2445,"filename": "boxart/front/176-1.jpg","resolution": "2100x1539"
},{
"id": 2446,"filename": "boxart/back/176-1.jpg","resolution": "2100x1533"
}
],"178": [
{
"id": 540,"filename": "boxart/front/178-1.jpg","resolution": "1000x690"
},{
"id": 541,"filename": "boxart/back/178-1.jpg","resolution": "2107x1473"
}
],"216": [
{
"id": 234524,"filename": "boxart/back/216-1.jpg","resolution": null
},{
"id": 235403,"filename": "boxart/front/216-1.jpg","228": [
{
"id": 2429,"filename": "boxart/front/228-1.jpg","resolution": "2100x1540"
},{
"id": 2430,"filename": "boxart/back/228-1.jpg","229": [
{
"id": 2431,"filename": "boxart/front/229-1.jpg","resolution": "2100x1524"
},{
"id": 2432,"filename": "boxart/back/229-1.jpg","resolution": "2100x1540"
}
],"230": [
{
"id": 538,"filename": "boxart/front/230-1.jpg","resolution": "1000x682"
},{
"id": 539,"filename": "boxart/back/230-1.jpg","resolution": "1000x687"
}
]
}
},"platform": {
"data": {
"3": {
"id": 3,"name": "Nintendo 64","alias": "nintendo-64"
}
}
}
},"pages": {
"previous": null,"current": "https://api.thegamesdb.net/v1/Games/ByPlatformID?apikey=8b574d53e9ff612a214486cfe8def1f5c045b0e4eaac50cfd54aa7873d89fd7b&id=3&fields=players%2Cpublishers%2Cgenres%2Coverview%2Clast_updated%2Crating%2Cplatform%2Ccoop%2Cyoutube%2Cos%2Cprocessor%2Cram%2Chdd%2Cvideo%2Csound%2Calternates&include=boxart%2Cplatform&page=1","next": "https://api.thegamesdb.net/v1/Games/ByPlatformID?apikey=8b574d53e9ff612a214486cfe8def1f5c045b0e4eaac50cfd54aa7873d89fd7b&id=3&fields=players%2Cpublishers%2Cgenres%2Coverview%2Clast_updated%2Crating%2Cplatform%2Ccoop%2Cyoutube%2Cos%2Cprocessor%2Cram%2Chdd%2Cvideo%2Csound%2Calternates&include=boxart%2Cplatform&page=2"
},"remaining_monthly_allowance": 2895,"extra_allowance": 0,"allowance_refresh_timer": 1014265
}
解决方法
我不清楚您的问题,尤其是关于i just scrolled past become a single image and stick
的问题,我在这里有几个问题:
您是否要在此tableview方法中添加图像?
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) ->
UITableViewCell
{
}
为什么要尝试从单元格保存imageview的引用
self.coverImage = cell.tableViewCoverImage.image!
您要附加图像的代码在哪里?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。