将图片从url下载到图片数组并以表格视图的形式显示

时间:2019-06-26 10:18:25

标签: swift uiimageview

我无法从json网址获取图片。

这是我的json:

"bank_details": [
    {
        "id": 1,
        "logo": "http://mortgagemarket.ae/webApi/public/mortgage_bank_icons/noorebank.png",
        "name": abc company

    }
]

我用来解析图像的快速代码是这样的:

import UIKit
class BanksViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {

final let BANKS_URL = "http://www.mortgagemarket.ae/webApi/api/manage_interest_rates"
    @IBOutlet weak var tableView: UITableView!

var bankicon = [String]()
var bankname = [String]()
var bankid = [Int]()

let stringid: String = ""

override func viewDidLoad() {
    super.viewDidLoad()

    self.displayFromDb()
    tableView.dataSource = self
    tableView.delegate = self


}



func displayFromDb()
{
    let tokensp = UserDefaults.standard.string(forKey: "tokenKey")
    let url = NSURL(string: BANKS_URL+"?token="+tokensp!)

    print(url)
    URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
        Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
        {

            print(jsonObj.value(forKey: "bank_details")!)

            if let messageArray = jsonObj.value(forKey: "bank_details") as? NSArray
            {
                print(jsonObj.value(forKey: "bank_details")!)

                for message in messageArray
                {
                    if let messageDict = message as? NSDictionary
                    {

                        if let data = data {


                            if let bankname = messageDict.value(forKey: "bank_name")
                            {
                                self.bankname.append(bankname as! String)
                                print(bankname)

                            }


                            if let banklogo = messageDict.value(forKey: "logo")
                            {

                                self.bankicon.append(banklogo as! String)
                                print(banklogo)

                            }

                            if let bankid = messageDict.value(forKey: "id")
                            {
                                self.bankid.append(bankid as! Int)
                                print(bankid)

                            }

                            OperationQueue.main.addOperation({
                                self.tableView.reloadData()
                            })

                        }
                    }

                }

            }

        }


    }).resume()

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (bankname.count)
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BanksTableViewCell



  cell.bankicon.image = bankicon[indexPath.row] as? UIImage
    cell.bankname.text = bankname[indexPath.row]


    return (cell)

}

}

现在,当我运行此代码时,它显示空白表格单元格。我不知道如何从url获取图像并在表格视图单元格中显示图像。请有人帮我。 这是我将所有json数据放入表格视图单元格的全部代码。请有人帮我

2 个答案:

答案 0 :(得分:2)

您的模型应如下所示:

/// Your response models
struct BankDetails: Codable {
    let bank_details: [ImageUrl]
}

struct ImageUrl: Codable {
    let logo: String
}

然后在您的单元格中

class MyCell: UITableViewCell {
    /// create dataTask for cancel in prepareForReuse function
    private var dataTask: URLSessionDataTask?

    /// Like this
    override public func prepareForReuse() {
        super.prepareForReuse()
        dataTask?.cancel()
    }

    func populate(with model: YourModel) {
        /// You should set url in indexPath of your logo array([ImageUrl])
        let url = model.url /// It's sample url for explain this is an url of your current index model
        if let imageUrl = url {
            downloaded(from: imageUrl)
        }
    }

    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        contentMode = mode
        dataTask = 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.yourImageView.image = image
            }
        }
        dataTask?.resume()
    }
}

在控制器的tableView cellForRowAt函数中:

let model = models[indexPath.row]
cell.populate(with: model)

return cell

您可以使用上述模型,并按以下方式创建displayFromDb:

func displayFromDb() {
    let tokensp = UserDefaults.standard.string(forKey: "tokenKey")
    let url = NSURL(string: BANKS_URL+"?token="+tokensp!)

    if let myUrl = url {
        URLSession.shared.dataTask(with: myUrl) { (data, response , error) in      
        guard let data = data else { return }
        do {
            let decoder = JSONDecoder()
            let data = try decoder.decode(BankDetails.self, from: data)
            print("my logo array is: \(data.bank_details)")
            // TODO: - So you get urls 

        } catch let err {
            print("Err", err)
        }
    }.resume()
    }

}

答案 1 :(得分:0)

imageicon [indexPath.row] gives a url字符串and not the instance of UIImage .您需要使用此image从服务器获取urlString

使用 URLSession 从服务器中获取图像,例如

if let url = URL(string: imageicon[indexPath.row]) {
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let data = data {
            DispatchQueue.main.async {
                cell.imageicon.image = UIImage(data: data)
            }
        }
    }.resume()
}