当我运行此代码时,它在我的collectionView中没有显示任何内容。我的代码 -
class ViewController:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet弱变…
请格式化您的下载代码,而不是将URL字符串保存到数组中以正确加载图像。我已经更新了代码。请参考下文。
//MARK: Image func downloadJson(){ let access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwMjc2LCJpc3MiOiJodHRwczovL2hvbWlpdGVzdC5jby56YS9hcGkvbG9naW4iLCJpYXQiOjE1NTIxOTYwMjIsImV4cCI6MTU1NDc4ODAyMiwibmJmIjoxNTUyMTk2MDIyLCJqdGkiOiJBeTY5R0JkZDA5dWdFTDBhIn0.czpQQsC08vuTB8iGdTeEjjQUmzl6I5Cs0VQ8WeA5VaY" let headers = ["Authorization": "Bearer "+access_token+"", "Content-Type": "application/json"] Alamofire.request("https://homiitest.co.za/api/gallery", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in if response.result.isSuccess{ //print(response) let swiftyJson = JSON(response.data!) let productTemplate = swiftyJson["data"].array //print("hello there - \(productTemplate)") for product in productTemplate! { // print(product["image_medium"].stringValue) self.AllImage.append(product.stringValue) print("this is data - \(product.stringValue)") } self.collectionView!.reloadData() } } }
如果您不想使用其他库,您仍然可以使用Alamofire AlamofireImage , AFNetworking , SDWebImage 等
extension UIImageView { func showImages(imageURL: String) { Alamofire.request(imageURL, method: .get) .validate() .responseData(completionHandler: { (responseData) in self.image = UIImage(data: responseData.data!) }) }}
你可以像这样使用它:
cell.myImage.showImages(AllImage[indexPath.row])
如果您不想安装pod,请尝试此操作。 让imageCache = NSCache()
extension UIImageView { func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) { self.image = nil if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) { self.image = cachedImage return } self.image = placeHolder if let url = URL(string: URLString) { URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in if error != nil { print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))") return } DispatchQueue.main.async { if let data = data { if let downloadedImage = UIImage(data: data) { imageCache.setObject(downloadedImage, forKey: NSString(string: URLString)) self.image = downloadedImage } } } }).resume() } } }
的 使用 : 强>
cell.myImage.imageFromServerURL(AllImage[indexPath.row], placeHolder:PLACEHOLDER_IMAGE)
如果您有任何疑问,请告诉我。
UIImage(named:String)从资产目录中加载图像。由于AllImage包含图像网址,因此您需要先显示每个图像,然后才能显示它们。我推荐使用图书馆( 翠鸟 是一个很棒的,相当容易使用)。 您需要替换此行代码
cell.myImage.image = UIImage(named: AllImage[indexPath.row])
同
let url = URL(string: AllImage[indexPath.row]) cell.myImage.kf.setImage(with: url)