代码之家  ›  专栏  ›  技术社区  ›  Alexa289

为什么我不能使用SDWebImage下载png格式的文件?

  •  0
  • Alexa289  · 技术社区  · 7 年前

    我正在调试我的代码,我发现为什么我的图像没有出现的问题是因为我无法使用SDWebImage下载png格式的文件。

    如果格式为jpg,则可以正常工作。下面是表视图控制器中的完整简化代码。

    class ViewController: UIViewController, UITableViewDataSource {
        @IBOutlet weak var tableView: UITableView!
    
        var imageURLs = [String]()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.dataSource = self
            imageURLs = ["https://app10.pakubuwono6.com/hris/images/notification/Logo Small.png", "https://app10.pakubuwono6.com/hris/images/notification/Logo Small.png", "https://app10.pakubuwono6.com/hris/images/notification/Logo Small.png", "https://app10.pakubuwono6.com/hris/images/notification/Logo Small.png"]
            tableView.reloadData()
        }
    
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return imageURLs.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellImage") as! CellImage
            cell.imageExample.sd_setImage(with: URL(string: imageURLs[indexPath.row]), placeholderImage: UIImage(named: "placeholder"), options: [.continueInBackground, .progressiveDownload])
            return cell
        }
    }
    

    我正在使用下面的代码行下载图像,我在该视图控制器的表视图单元格中设置图像

    cell.imageExample.sd_setImage(with: URL(string: imageURLs[indexPath.row]), placeholderImage: UIImage(named: "placeholder"), options: [.continueInBackground, .progressiveDownload])
    

    这里出了什么问题?

    只显示占位符图像 enter image description here

    2 回复  |  直到 7 年前
        1
  •  3
  •   a.masri    7 年前

    您的图像url包含空白 尝试此代码

    if let url = imageURLs[indexPath.row].addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed){
     cell.imageExample.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "placeholder"), options: [.continueInBackground, .progressiveDownload])
    
    }
    
        2
  •  3
  •   Duncan C    7 年前

    你没有显示 setImage(with:placeholderImage:options:) 方法加载图像,所以很难判断到底发生了什么。

    然而,一个明显的问题是,图像URL包含未转义的空格。您应该像这样更改URL:

    imageURLs = 
      ["https://app10.pakubuwono6.com/hris/images/notification/Logo%20Small.png", 
      "https://app10.pakubuwono6.com/hris/images/notification/Logo%20Small.png", 
      "https://app10.pakubuwono6.com/hris/images/notification/Logo%20Small.png", 
      "https://app10.pakubuwono6.com/hris/images/notification/Logo%20Small.png"]
    

    (请注意,您不能使用 addingPercentEncoding 因为URL字符串中的其他符号不应转义,只应转义文件名。)

    使用 URLComponents . 指定URL的不同部分,然后询问 URL组件 为您提供URL。它可以为您正确地转义不同的组件。