在本教程的这一部分中,无涯教程将找到处理iOS应用程序中的后台任务的方法。在这里,无涯教程将改进在本教程前面各节中构建的应用程序之一,这是无涯教程创建的Artist Project,用于向用户显示Artist数据。
现在,无涯教程将使用多线程来改善Artist Project的性能。在Artist Project中,无涯教程已经在主线程的viewDidLoad()中执行了图像缓存。但是,这可以作为后台任务异步执行。在这里,无涯教程必须注意,所有UI更新任务都必须始终位于主线程上。
以下代码用于使用全局调度队列在后台执行图像缓存。
DispatchQueue.global(qos: .background).async { [weak self] in debugPrint("performing image caching") guard let self = self else{ return } for i in result.results ?? []{ Alamofire.request(i.artworkUrl60!).responseImage { (response) in if response.result.value != nil{ let image = UIImage(data: response.data!, scale: 1.0) self.imageCache.add(image!, withIdentifier: i.artworkUrl60! ) } } } DispatchQueue.main.sync { debugPrint("reloading tableview") self.tableView.reloadData() } }
这将使viewDidLoad(:)在缓存图像并重新加载表格视图之前结束。在这里,无涯教程必须注意,表视图已在主线程上重新加载,并且所有UI更新都必须始终在主线程上进行。
修改后的ViewController.swift如下所示。
// // ViewController.swift // ParseJsonData // // Created by Ayush Sharma on 06/08/19. // Copyright ? 2019 Apple Inc. All rights reserved. // import UIKit import Alamofire import AlamofireImage class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var artist = Array() let imageCache = AutoPurgingImageCache(memoryCapacity: 111_111_111, preferredMemoryUsageAfterPurge: 90_000_000) override func viewDidLoad() { super.viewDidLoad() //Do any additional setup after loading the view. loadJsonData() tableView.delegate = self tableView.dataSource = self //tableView.rowHeight = UITableView.automaticDimension } func loadJsonData() { Alamofire.request("https://itunes.apple.com/search?media=music&term=bollywood").responseJSON { (response) in //print("Response value \(response)") do{ if(response.result.isSuccess){ let result: ArtistResponseModel = try JSONDecoder().decode(ArtistResponseModel.self, from: response.data!) debugPrint(result) self.artist = result.results ?? [] DispatchQueue.global(qos: .background).async { [weak self] in debugPrint("performing image caching") guard let self = self else{ return } for i in result.results ?? []{ Alamofire.request(i.artworkUrl60!).responseImage { (response) in if response.result.value != nil{ let image = UIImage(data: response.data!, scale: 1.0) self.imageCache.add(image!, withIdentifier: i.artworkUrl60! ) } } } DispatchQueue.main.sync { debugPrint("reloading tableview") self.tableView.reloadData() } } } }catch{ } } debugPrint("end of view did load") } } extension ViewController : UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return artist.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell") as! MainTableViewCell if(artist.count > 0){ let artistData = artist[indexPath.row] DispatchQueue.main.async { cell.artistImgView.image = self.imageCache.image(withIdentifier: artistData.artworkUrl60!) } cell.trackName.text = artistData.trackName cell.artisName.text = artistData.artistName cell.artistCountry.text = artistData.country } return cell } } extension ViewController : UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 220 } }
由于无涯教程在代码中使用了打印语句,因此让无涯教程来看看下面给出的控制台输出。
"end of view did load" ArtistProject.ArtistResponseModel "performing image caching" "reloading tableview"
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Python实战 · 从0到1搭建直播视频平台 -〔Barry〕