Swift:为什么我的IOS应用程序速度变慢

时间:2017-12-13 07:36:26

标签: swift web-services tableview

我使用WebServices(SOAP)来访问数据。我从数据库中获取图像URL,下载它们并在TableView中显示。这是我的代码。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "gorevlerCell",for: indexPath) as! GorevlerCell
    cell.contentView.backgroundColor = UIColor(white: 0.95, alpha: 1)

    // Fil the gorevler Cell

    cell.txtGorevAdi.text = (gorevler.object(at: indexPath.row) as AnyObject).value(forKey: "Gorev_Adi") as? String
    cell.txtGoreviAlan.text = (gorevler.object(at: indexPath.row) as AnyObject).value(forKey: "Gorevi_Alan") as? String
    cell.txtGoreviVeren.text = (gorevler.object(at: indexPath.row) as AnyObject).value(forKey: "Gorevi_Veren") as? String
    cell.txtTarih.text = (gorevler.object(at: indexPath.row) as AnyObject).value(forKey: "Tarih") as? String
    cell.txtOncelikDurumu.text = (gorevler.object(at: indexPath.row) as AnyObject).value(forKey: "Oncelik_Durumu") as? String


    // The Image File
    let imgUrl2 = (gorevler.object(at: indexPath.row) as AnyObject).value(forKey: "Profil_Url") as? String
    let trimmedImgUrl = imgUrl2?.trimmingCharacters(in: .whitespaces)
    let url = NSURL( string : "http://"+trimmedImgUrl! )
    let data = NSData(contentsOf: url! as URL)
    let img = UIImage(data: data! as Data)
    cell.profileImage.image = img
    cell.profileImage.layer.cornerRadius = 35
    cell.profileImage.layer.borderWidth = 2.0
    cell.profileImage.layer.borderColor = UIColor.lightgray.cgColor
    cell.profileImage.clipsToBounds = true

    return cell}

所以,当我在TableView中添加图像并滚动它时,应用程序开始变慢。我的问题是为什么应用程序运行缓慢以及如何加快它。

注意:我可以试用低分辨率图像,但仍然很慢。

1 个答案:

答案 0 :(得分:2)

它很慢,因为你是同步下载图像。

您需要异步下载它。请考虑以下示例:

在您的应用中添加以下扩展程序。

extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
            else { return }
            DispatchQueue.main.async() { 
                self.image = image
            }
        }.resume()
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
}

你可以在你的情况下使用它:

cell.profileImage.downloadedFrom(link: "http://"+trimmedImgUrl!)

将以上行替换为:

let url = NSURL( string : "http://"+trimmedImgUrl! )
let data = NSData(contentsOf: url! as URL)
let img = UIImage(data: data! as Data)
cell.profileImage.image = img

有关详细信息,请查看original帖子。